[英]C# Search for a word occurances within a string
How can I search for a word within a string ? 如何在字符串中搜索单词? I have one text box which the user insert a string and another on with with text just some random text. 我有一个文本框,用户可在其中插入一个字符串,而另一个文本框仅带有一些随机文本。 Are there any alterative ways of doing this besides using regex
and IndexOf
? 除了使用regex
和IndexOf
之外,还有其他替代方法吗? Like using a for loop
and checking the length and character in the word. 就像使用for loop
并检查单词的长度和字符一样。
This is what I tried so far 这是我到目前为止尝试过的
int i = 0;
int count = 0;
input2.Trim();
while ((i = input2.IndexOf(input1, i)) != -1)
{
i = i + input1.Length;
count++;
}
MessageBox.Show(count.ToString() + " Matches Found");
Looks like you want to get the Count of search string in the text. 看起来您想获取文本中的搜索字符串计数。 You can try the following. 您可以尝试以下方法。
string searchString = "TEST";
string completeText = "Some sentence TEST with other words incluing TEST";
int count = completeText.Split(new string[]{"TEST"},StringSplitOptions.None)
.Count() - 1;
MessageBox.Show(count.ToString() + " Matches Found");
Use a regex to match the number of occurances, 使用正则表达式来匹配出现次数,
string test = "THE DOG WENT TO TOWN DOG";
int j = Regex.Matches(test, "DOG").Cast<Match>().Count();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.