2012-01-10 132 views
2

我想查找字符串完全匹配的次数 假设字符串是“我的电脑”。我想找到它,S出现在字符串查找HTML文件中字符串的确切出现次数

这是我的电脑,这是一个很好的电脑,
这是我的电脑,这是我的计算机

所以在最后我将得到计数2,

我试过以下公式'mykeyWord'作为字符串被发现。

int strength = (innerDocument.DocumentNode.InnerText.Length - innerDocument.DocumentNode.InnerText.ToLower().Replace(mykeyWord.ToLower(), "").Length)/mykeyWord.Length; 

但它也会计算像'我的电脑'这样的字符串是错误的。

回答

4

这是使用正则表达式一个完美的地方,就像你标记您的文章:

Regex re = new Regex("\\b" + Regex.Escape(mykeyWord) + "\\b", RegexOptions.IgnoreCase); 
int count = re.Matches(innerDocument.DocumentNode.InnerText).Count; 
+0

请您解释一下这个正则表达式模式。 – 2012-01-11 02:58:21

+0

@ZainAli:'\ b'匹配单词边界,即任何不是单词的东西。标点符号,空格等等。它将夹在中间的转义关键字夹在中间以匹配。 – Ryan 2012-01-11 03:04:40

1

你可以使用正则表达式[^A-z](my computer)[^A-z]这符合“我的电脑”但如果它之前或“A后到Z'。要使正则表达式搜索不区分大小写,请使用RegexOptions.IgnoreCase

编辑 minitech的使用词边界的答案是更好的。

1
int FindCount(string keyword, string input) 
    { 
     if (input.Contains(keyword)) 
     { 
      int count = 0; 
      int i = 0; 
      foreach (var c in input) 
      { 
       if (c == keyword[i]) 
        i++; 
       else 
        i = 0; 
       if (i == keyword.Length) 
       { 
        i = 0; 
        count++; 
       } 
      } 
      return count; 
     } 

     return 0; 
    } 
相关问题