【问题标题】:Get number of replacements [duplicate]获取替换数量[重复]
【发布时间】:2014-12-14 01:15:35
【问题描述】:

有没有使用.Replace("a", "A");获取替换次数的方法?

Example:

String string_1 = "a a a";
String string_2 = string_1.Replace("a", "A"); 

在这种情况下,输出应该是 3,因为 a 被替换为 A 3 次。

【问题讨论】:

    标签: c# .net string replace numbers


    【解决方案1】:

    您可以使用.Split 函数获取计数:

     string_1.Split(new string[] { "a" }, StringSplitOptions.None).Length-1;
    

    拆分字符串后,我们会多得到一项。因为,.Split 函数返回一个字符串数组,其中包含此字符串中由指定字符串数组的元素分隔的子字符串。因此,Length 属性的值将是 n+1

    【讨论】:

    【解决方案2】:

    您可以使用Regex.Matches 方法找出要替换的内容。如果字符串包含任何会被特别视为正则表达式的字符,请使用Regex.Escape 方法对字符串进行转义。

    int cnt = Regex.Matches(string_1, Regex.Escape("a")).Count;
    

    【讨论】:

      【解决方案3】:

      您不能直接使用 string.Replace 执行此操作,但您可以使用 string.IndexOf 搜索您的字符串,直到找不到匹配项

      int counter = 0;
      int startIndex = -1;
      string string_1 = "a a a";
      while((startIndex = (string_1.IndexOf("a", startIndex + 1))) != -1)
          counter++;
      Console.WriteLine(counter);
      

      如果这变得经常使用,那么您可以计划创建一个extension method

      public static class StringExtensions
      {
           public static int CountMatches(this string source, string searchText)
           {
      
              if(string.IsNullOrWhiteSpace(source) || string.IsNullOrWhiteSpace(searchText))
                 return 0;
      
               int counter = 0;
               int startIndex = -1;
               while((startIndex = (source.IndexOf(searchText, startIndex + 1))) != -1)
                   counter++;
               return counter;
           }
      }
      

      并调用它

      int count = string_1.CountMatches("a");
      

      IndexOf 的优点在于您不需要创建字符串数组 (Split) 或对象数组 (Regex.Matches)。这只是一个涉及整数的普通循环。

      【讨论】:

        猜你喜欢
        • 2017-10-02
        • 2017-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-17
        • 2014-01-09
        • 2014-07-29
        相关资源
        最近更新 更多