【问题标题】:How to check repeated letters in a string c#如何检查字符串中重复的字母c#
【发布时间】:2013-08-08 18:09:17
【问题描述】:

我正在创建一个检查字符串中重复字母的程序。

例如:

呜呜呜呜呜呜
happpppppppy

这是我的代码:

 string repeatedWord = "woooooooow";
 for (int i = 0; i < repeatedWord.Count(); i++)
 {
     if (repeatedWord[i] == repeatedWord[i+1])
     {
          // ....
     }
 }

代码可以运行,但总是会出错,因为最后一个字符 [i + 1] 为空/null。

错误是索引超出了数组的范围。

有什么解决办法吗?

【问题讨论】:

  • repeatedWord.Count() - 1
  • 很清楚:如果你寻找 +1 索引,你不能迭代到最后一个位置。 repeatWord.Count() - 1 应该是最大值。
  • 如果您有一个长度为 10 个元素的数组,则无法尝试读取第 11 个元素。您是否在调试器中单步执行了“for”循环以查看发生了什么?
  • 您是在寻找顺序重复还是整个字符串中的任何字符重复?您也有兴趣了解重复的实际字符,还是只想得到bool 结果?
  • 你的目标是什么?你想得到重复字符的数量吗?目前尚不清楚您的目标是什么。

标签: c# string if-statement


【解决方案1】:

循环运行直到repeatedWord.Count()-1

【讨论】:

  • 你会错过最后一个字母吗?
  • @JeroenvanLangen 你想检查最后一个字母到底是什么?它总是不同于“行尾”。
  • @JeroenvanLangen new[] { 0, 1, 2 }.Count() == 3
  • 没错,没错,最后一个字母 = [i+1] 错过了... ;) 我宁愿避免在代码中使用 index+1。可读性会降低,并迫使程序员使用 count-1 等内容。因此可能会导致更多“奇怪”的行为
  • 如果你这样做,你需要从第二个字符开始,否则你会因为查找第一个字符之前的字符而失败。
【解决方案2】:

正则表达式:

Regex rxContainsMultipleChars = new Regex( @"(?<char>.)\k<char>" , RegexOptions.ExplicitCapture|RegexOptions.Singleline ) ;
.
.
.
string myString = SomeStringValue() ;
bool containsDuplicates = rxDupes.Match(myString) ;

或 Linq

string s = SomeStringValue() ;
bool containsDuplicates = s.Where( (c,i) => i > 0 && c == s[i-1] )
                           .Cast<char?>()
                           .FirstOrDefault() != null
                           ;

或自己动手:

public bool ContainsDuplicateChars( string s )
{
  if ( string.IsNullOrEmpty(s) ) return false ;

  bool containsDupes = false ;
  for ( int i = 1 ; i < s.Length && !containsDupes ; ++i )
  {
    containsDupes = s[i] == s[i-1] ;
  }

  return containsDupes ;
}

甚至

public static class EnumerableHelpers
{
  public static IEnumerable<Tuple<char,int>> RunLengthEncoder( this IEnumerable<char> list )
  {
    char? prev  = null ;
    int   count = 0 ;

    foreach ( char curr in list )
    {
      if      ( prev == null ) { ++count ; prev = curr ; }
      else if ( prev == curr ) { ++count ;               }
      else if ( curr != prev )
      {
        yield return new Tuple<char, int>((char)prev,count) ;
        prev = curr ;
        count = 1 ;
      }
    }
  }
}

最后一个...

bool hasDupes = s.RunLengthEncoder().FirstOrDefault( x => x.Item2 > 1 ) != null ;

foreach (Tuple<char,int> run in myString.RunLengthEncoder() )
{
  if ( run.Item2 > 1 )
  {
     // do something with the run of repeated chars.
  }
}

【讨论】:

    【解决方案3】:

    另一种选择是使用匹配重复字符的正则表达式。然后,对于每个匹配项,您可以使用Length 属性获取字符数。

    string input = "wooooooow happppppppy";
    var matches = Regex.Matches(input, @"(.)\1+");
    for (int i = 0; i < matches.Count; i++)
    {
        Console.WriteLine("\"" + matches[i].Value + "\" is " + matches[i].Length + " characters long.");
        //...
    }
    Console.Read();
    

    【讨论】:

      【解决方案4】:

      只要“记住”我要说的最后一个字母。

      string repeatedWord = "woooooooow";
      if (string.IsNullOrEmpty( repeatedWord))
          // empty. return, throw whatever.
      
      char previousLetter = repeatedWord[0]; 
      for (int i = 1; i < repeatedWord.Count(); i++)
      {
          if (repeatedWord[i] == previousLetter)
          {
              // ....              
          }
          else
          previousLetter = repeatedWord[i];
      }
      

      【讨论】:

        【解决方案5】:
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;
        
        namespace Delegate
        {
            class Program
            {
               public int repeatcount(string str,char ch)
                {
        
                    var count = 0;
                    for (int i = 0; i<str.Length; i++)
                    {
                        if (ch == str[i])
                        {
                            count++;
                        }
        
                    }
        
                    return count;
                }
                static void Main(string[] args)
                {
                    Console.WriteLine("Enter a string");
                    string str = Console.ReadLine();
                    Console.WriteLine("Enter to know the reperted char");
                    char ch = Convert.ToChar(Console.ReadLine());
                    Program obj = new Program();
                    int p=obj.repeatcount(str, ch);
                    Console.WriteLine(p);
        
        
                    Console.ReadLine();
        
                }
            }
        
        
        
        }
        

        【讨论】:

          【解决方案6】:

          您可以更改循环条件以使用-1(正如其他人已经指出的那样),或者您可以用酷孩子的方式来做。

          var text = "wooooooooooow happpppppppy";
          var repeats = text.Zip(text.Skip(1), (a, b) => a == b).Count(x => x);
          

          【讨论】:

          • 你好蒂莫西!你能解释一下代码是怎么做的吗
          【解决方案7】:
           public int RepeatedLetters(string word)
                  {
                      var count = 0;
                      for (var i = 0; i < word.Count()-1; i++)
                      {
                          if (word[i] == word[i+1])
                          {
                              count++;
                          }
                      }
                      return count;
                  }
          

          【讨论】:

          • 在计数中,我们可以得到重复字符的值
          • 你最好解释更多细节
          【解决方案8】:
          using System;
          
          namespace temp1
          {
              class Program
              {
                  static string str = "proffession";
                  static int n = str.Length;
                  static string dupstr = "";
                  static int cnt = 0;
                  static void Main()
                  {
                      RepeatedCharsString(); 
                  }
          
                  public static void RepeatedCharsString()
                  {
                      for (int i = 0; i < n ; i++)
                      {
                          for(int j = i + 1; j <= n-1; j++)
                          {
                              if (str[i] == str[j])
                              {
                                  dupstr = dupstr + str[i];
                                  cnt = cnt + 1;
                              }
                          }                
                      }
                      Console.WriteLine("Repeated chars are: " + dupstr);
                      Console.WriteLine("No of repeated chars are: " + cnt);
                  }
              }
          }
          

          【讨论】:

            【解决方案9】:

            你也可以这样做:

            string myString = "longstringwithccc";
            var list = new List<char>();
            var duplicates = new List<char>();
            foreach(char c in myString)
            {
               if (!list.Contains(c))
               {
                  list.Add(c);
               }
               else
               {
                  if (!duplicates.Contains(c))
                  {
                     duplicates.Add(c);
                  }
               }
            }
            

            duplicates 将包含原始字符串中的重复字符。

            list 将包含删除重复项的原始字符串。

            【讨论】:

              【解决方案10】:

              您运行循环一次迭代的时间过长。

              或者,您可以使用 LINQ 查找单词中的唯一(不同)字符,然后检查它们在单词中的出现。如果它多次出现,请对其进行处理。

              void RepeatedLetters()
              {
                  string word = "wooooooow";
                  var distinctChars = word.Distinct();
                  foreach (char c in distinctChars)
                      if (word.Count(p => p == c) > 1)
                      { 
                          // do work on c
                      }
              }
              

              【讨论】:

              • @I4V 你是对的。这不限于连续重复。
              • 如果你确实想解决这个问题,而不是 OP 的问题,你会想使用GroupByCount。该解决方案多次迭代序列;这是非常糟糕的表现。
              • 正如@Servy 所说。这,s.GroupBy( c =&gt; c ).FirstOrDefault( group =&gt; group.Count() &gt; 1 ) != null ;(或类似的东西)将以更少的工作完成同样的事情。我相信您的代码将在大约 O(n*^2) 时间内运行。 O(*mn) 实际上,其中 m 是源中不同字符的计数,而 n 是源中字符的总数。
              • @NicholasCarey & Servy - 同意。
              【解决方案11】:

              使用 C# 在给定字符串中查找重复或重复的字母

              string str = "Welcome Programming";
              char[] Array = str.ToCharArray();
              var duplicates = Array.GroupBy(p => p).Where(g => g.Count() > 1).Select(g => g.Key).ToList();
              string duplicateval= string.Join(",", duplicates.ToArray());
              

              输出:

              e,o,m,r,g

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2016-07-06
                • 2019-04-28
                • 1970-01-01
                • 2013-10-09
                • 1970-01-01
                • 1970-01-01
                • 2017-12-25
                • 1970-01-01
                相关资源
                最近更新 更多