问题描述
- 为什么最后一个for语句里的截取字符语句总是出错,大神们帮帮忙啊。。
-
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;namespace TJ
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}private void Form1_Load(object sender, EventArgs e) { } public int Pd(string s) { int len = s.Length; //s=str.Substring(str.Length-i); // or str=str.Remove(0,str.Length-i); k = k.Substring(k.Length-1, 1); // string str = s.Substring(s.Length -1,1); //s = s.Remove(s.LastIndexOf(","), 1); /* if (str==","||str==".") { s = s.Remove(s.Length - 2,s.Length -1); }*/ ListViewItem li = new ListViewItem(); for (int i = 0; i < listView1.Items.Count; i++) { if (listView1.Items[i].SubItems[0].Text == s) { return 0; } } return 1; } public int Pdc(string[] sj,string s) { int tem=0; for (int i = 0; i < sj.Length; i++) { if (s == sj[i]) tem++; } return tem; } private void button1_Click(object sender, EventArgs e) { string center = txtDate.Text; string str = center.ToLower(); string[] parm = str.Split(' '); int len = parm.Length; this.listView1.View = View.Details; this.listView1.GridLines = true; this.listView1.HeaderStyle = ColumnHeaderStyle.Nonclickable; this.listView1.Columns.Add("词汇", 120, HorizontalAlignment.Right); this.listView1.Columns.Add("出现次数", 120, HorizontalAlignment.Right); this.listView1.Visible = true; for (int i = 0; i < len; i++) { string s = parm[i]; s = s.Remove(s.LastIndexOf(","), 1); int tem = Pd(parm[i]); if (tem == 1 && parm[i] != "") { int m = Pdc(parm, parm[i]); string mm = Convert.ToString(m); ListViewItem li = new ListViewItem(); li.SubItems[0].Text = parm[i].ToString(); li.SubItems.Add(mm); this.listView1.Items.Add(li); } } } }
}
解决方案
你好,我觉得问题应该出在这里:
string s = parm[i];
s = s.Remove(s.LastIndexOf(","), 1);
首先,s.LastIndexOf(string),会返回string在s中首次出现的位置,若未出现,则返回-1,s.Remove(StartIndex, 1)会在s的StartIndxe位置开始删除1个字符。
IDE报的错误是"StartIndex不能小于0",所以错误原因应该是parm[i]中不包含",",建议楼主检查一下parm[]中的数据。
解决方案二:
private void button1_Click(object sender, EventArgs e)
{
this.listView1.View = View.Details;
this.listView1.GridLines = true;
this.listView1.HeaderStyle = ColumnHeaderStyle.Nonclickable;
this.listView1.Columns.Add("词汇", 120, HorizontalAlignment.Right);
this.listView1.Columns.Add("出现次数", 120, HorizontalAlignment.Right);
this.listView1.Visible = true;
var query = txtDate.Text.ToLower().Split(' ').GroupBy(x => x);
foreach (var item in query)
{
ListViewItem li = new ListViewItem();
li.Text = item.Key.ToString();
li.SubItems[0].Text = item.Count().ToString();
this.listView1.Items.Add(li);
}
}
解决方案三:
我觉得你应该描述下什么错误
时间: 2024-12-26 20:58:29