【问题标题】:Count a word inside a long string in c# [duplicate]在c#中计算一个长字符串中的一个单词[重复]
【发布时间】:2014-12-17 16:10:40
【问题描述】:

你能解释一下我如何以简单的方式找到某个字符串在一个大字符串中出现的次数吗? 示例:

  string longString = "hello1 hello2 hello546 helloasdf";

“你好”这个词出现了四次。我怎样才能得到第四个。 谢谢

编辑:我也想知道如何找到两个单词的字符串,例如:

 string longString = "hello there hello2 hello4 helloas hello there";

我想知道“hello there”出现的次数。

编辑 2:正则表达式方法对我来说是最好的(计数),但它找不到像这样的单词,例如: ">word”的单词,它会跳过它。帮忙?

【问题讨论】:

标签: c# string search count word


【解决方案1】:

只需使用string.Split() 并计算结果:

string wordToFind = "hello";

string longString = "hello1 hello2 hello546 helloasdf";
int occurences = longString
                     .Split(new []{wordToFind}, StringSplitOptions.None)
                     .Count() - 1;

//occurences = 4

要回答您的编辑,只需将 wordToFind 更改为 hello there

【讨论】:

    【解决方案2】:
    string longString = "hello1 hello2 hello546 helloasdf";
    var regex = new Regex("hello");
    
    var matches = regex.Matches(longString);
    Console.WriteLine(matches.Count);
    

    【讨论】:

    • 嗨,这对我来说是最好的方法,但是当我想要一个包含 ">word请帮忙。谢谢
    【解决方案3】:

    使用 LINQ 执行此操作:

    int count = 
        longString.Split(' ')
        .Count(str => str
        .Contains("hello", StringComparison.InvariantCultureIgnoreCase));
    

    这里唯一的假设是您的 longString 由空格分隔。

    【讨论】:

      【解决方案4】:

      您也可以使用 Linq 来执行此操作。

      string longString = "hello1 hello2 hello546 helloasdf";
      string target = "hello";
      var count = longString.Split(' ').ToList<string>().Count(w => w.Contains(target));
      Console.WriteLine(count);
      

      【讨论】:

        猜你喜欢
        • 2013-03-14
        • 2018-10-22
        • 2016-06-24
        • 1970-01-01
        • 1970-01-01
        • 2012-10-04
        • 1970-01-01
        • 2019-04-24
        • 1970-01-01
        相关资源
        最近更新 更多