【问题标题】:How to check if string contains single occurence of substring?如何检查字符串是否包含单个出现的子字符串?
【发布时间】:2013-02-08 15:01:14
【问题描述】:

我有这个:

string strings = "a b c d d e";

我需要类似于string.Contains() 的东西,但我不仅需要知道是否存在字符串(如果是字母以上),还需要知道是否只存在一次

我怎样才能做到这一点?

【问题讨论】:

标签: c# string


【解决方案1】:

您可以使用LastIndexOf(String)IndexOf(String) 并验证返回的值是否相等。当然还要检查是否找到了字符串(即返回值不是-1)。

【讨论】:

  • 其实后者只是IndexOf(String),没有“First”。
【解决方案2】:

你可以使用 LINQ

int count = strings.Count(f => f == 'd');

【讨论】:

  • -1 Andrew 这很好,但条件不应该是硬编码
  • 这仅适用于字符。他提到他想在原始字符串中找到一个完整的字符串。
  • Bit Destroyer - 没错,我错过了
【解决方案3】:

另一种选择

if(Regex.Matches(input,Regex.Escape(pattern)).Count==1)

【讨论】:

    【解决方案4】:

    另一个简单的选择:

    if(strings.Split(new [] { "a" }, StringSplitOptions.None).Length == 2)
    

    【讨论】:

      【解决方案5】:

      试试下面...它会帮助你...

      string strings = "a b c d d e";
      string text ="a";
      int count = 0;
      int i = 0;
      while ((i = strings.IndexOf(text, i)) != -1)
      {
          i += text.Length;
          count++;
      }
      if(count == 0)
      Console.WriteLine("String not Present");
      
      if(count == 1)
      Console.WriteLine("String Occured Only one time");
      
      if(Count>1)
      Console.WriteLine("String Occurance : " + count.Tostring());
      

      【讨论】:

      • 您似乎混淆了 stringstext 变量。例如当你说text.IndexOf(text, i)。请注意,了解搜索字符串是否作为两个重叠的子字符串存在可能会很有趣。就像我们在"XXXXXreassureassureXX" 中搜索子字符串"reassure" 一样,可能需要计算两个匹配项(问题中并不清楚)。所以看你增加了多少i。还要注意i 的增量,因为如果超出strings 变量的范围,下一个IndexOf 将抛出异常,而不仅仅是返回-1
      • 首先使用strings = "a b c d d e"text = "e" 尝试您自己的代码。解决该问题后,尝试使用strings = "XXXXXreassureassureXX"text = "reassure" 进行编码。在这种情况下,你更喜欢什么答案?
      【解决方案6】:
          string source = "a b c d d e";
          string search = "d";
          int i = source.IndexOf(search, 0);
          int j = source.IndexOf(search, i + search.Length);
          if (i == -1)
              Console.WriteLine("No match");
          else if (j == -1)
              Console.WriteLine("One match");   
          else
              Console.WriteLine("More match");
      

      【讨论】:

        猜你喜欢
        • 2011-11-09
        • 2013-05-18
        • 1970-01-01
        • 1970-01-01
        • 2021-12-20
        • 1970-01-01
        • 2011-03-29
        • 2017-10-11
        • 2010-12-19
        相关资源
        最近更新 更多