c sharp中的文本比较 [英] Text Comparison in c sharp
问题描述
我写了一个程序来突出显示单词列表中的文本。例如男孩是好人,如果我想使用indexOf突出显示男孩,它将突出显示。现在的问题是像男孩是个好孩子这样的陈述,如果我想突出第二个男孩,我不知道如何,因为它只有第一个男孩仍然会突出显示。请帮助,因为我仍然是一些新的c sharp。
I wrote a program to highlight a text in a list of words. For example "The boy is a good", if i want to highlight "boy" using indexOf, it will be highlighted. now the problem is for a statement like "The boy is a good boy", if i want to highlight the second boy, i dont know how, because its only the first boy that will still be highlighted. Pls help as am still some how new to c sharp.
推荐答案
两个选项:
使用String.IndexOf
:
Two options:
usingString.IndexOf
:
int SecondIndexOf(string theString, string toFind)
{
int first = theString.IndexOf(toFind);
if (first == -1) return -1;
// Find the "next" occurrence by starting just past the first
return theString.IndexOf(toFind, first + 1);
}
使用正则表达式
:
Using Regex
:
public static int NthIndexOf(this string target, string value, int n)
{
Match m = Regex.Match(target, "((" + value + ").*?){" + n + "}");
if (m.Success)
return m.Groups[2].Captures[n - 1].Index;
else
return -1;
}
干杯,
Edo
Cheers,
Edo
首先,你必须检查条件,当它找到然后给它的索引时,该行中有多少次......
First You Have To Check Condition That How Many Times That Word Is In That Row When Its Find Then Give Index Of It....
也许这可能有所帮助。此函数定位您要查找的所有文本:
Perhaps this could help. This function locates all the occurrences of the text you're looking for:
private List<Match> FindOccurrences( string SourceText, string Expression )
{
List<Match> Result = new List<Match>();
Regex Parser = new Regex( Expression, RegexOptions.Compiled );
Match Match = Parser.Match( SourceText );
while (Match.Success)
{
Result.Add( Match );
Match = Match.NextMatch();
}
return Result;
}
你可以像这样调用这个函数:
You can call the function simply like this:
List<Match> Matches = FindOccurrences( "This contains boy here and again contains boy here", "boy" );
物业 类型对象的索引
匹配包含输入字符串中的位置。
The property Index
of the objects of type Match
contains the position into the input string.
这篇关于c sharp中的文本比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!