void lvnf_SelectedIndexChanged(object sender, EventArgs e)
{
results = new List<int>();
richTextBox1.Text = File.ReadAllText(listViewCostumControl1.lvnf.Items[listViewCostumControl1.lvnf.SelectedIndices[0]].Text);
FileInfo fi = new FileInfo(listViewCostumControl1.lvnf.Items[listViewCostumControl1.lvnf.SelectedIndices[0]].Text);
lblfilesizeselected.Text = ExtensionMethods.ToFileSize(fi.Length);
lblfilesizeselected.Visible = true;
filePath = Path.GetDirectoryName(fi.FullName);
string words = textBox1.Text;
string[] splittedwords = words.Split(new string[] { ",," }, StringSplitOptions.None);
foreach (string myword in splittedwords)
{
HighlightPhrase(richTextBox1, myword, Color.Yellow);
lblviewerselectedfile.Text = results.Count.ToString();
lblviewerselectedfile.Visible = true;
if (results.Count > 0)
{
numericUpDown1.Maximum = results.Count;
numericUpDown1.Enabled = true;
richTextBox1.SelectionStart = results[(int)numericUpDown1.Value - 1];
richTextBox1.ScrollToCaret();
}
}
}
這是進行拆分的行:
string[] splittedwords = words.Split(new string[] { ",," }, StringSplitOptions.None);
問題是如果我輸入 textBox1,例如 sadsdss,,s,,form1,,,,,,,,,f,,dd,,,,,,
然后所有超過兩個逗號的地方在突出顯示單詞時都算作空字串:
void HighlightPhrase(RichTextBox box, string phrase, Color color)
{
int pos = box.SelectionStart;
string s = box.Text;
for (int ix = 0; ;)
{
int jx = s.IndexOf(phrase, ix, StringComparison.CurrentCultureIgnoreCase);
if (jx < 0)
{
break;
}
else
{
box.SelectionStart = jx;
box.SelectionLength = phrase.Length;
box.SelectionColor = color;
ix = jx 1;
results.Add(jx);
}
}
box.SelectionStart = pos;
box.SelectionLength = 0;
}
例外是就行了:
int jx = s.IndexOf(phrase, ix, StringComparison.CurrentCultureIgnoreCase);
System.ArgumentOutOfRangeException: '索引超出范圍。必須是非負的并且小于集合的大小。引數名稱:startIndex'
因為短語是空字串 ""
我想要做的是,每個地方都有兩個以上的逗號,例如 ,,, 即使用戶鍵入 s,,1,,form1,,,,,, 也將其視為字串
所以單詞 s 1 form1 和 ,,,,,, 都應該算作結果和應該突出顯示的單詞。
uj5u.com熱心網友回復:
如果您想洗掉空條目,只需借助StringSplitOptions.RemoveEmptyEntries選項即可:
string[] splittedwords = words.Split(
new string[] { ",," },
StringSplitOptions.RemoveEmptyEntries);
另一種可能性是在Linq的幫助下進行查詢,如果您想排除(過濾掉)某些單詞,這會很有幫助,例如
using System.Linq;
...
string[] splittedwords = words
.Split(new string[] { ",," }, StringSplitOptions.None)
.Where(item => !string.IsNullOrWhiteSpace(item))
.ToArray();
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/403409.html
標籤:
