如何检查字符串c#中的重复字母

时间:2013-08-08 18:09:17

标签: c# string if-statement

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

例如:

  

wooooooooooow
happpppppppy

这是我的代码:

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

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

  

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

任何解决方案?

10 个答案:

答案 0 :(得分:10)

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

答案 1 :(得分:2)

只要“记住”我会说的最后一封信。

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];
}

答案 2 :(得分:2)

另一种选择是使用匹配重复字符的正则表达式。然后,对于每个匹配,您可以使用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();

答案 3 :(得分:1)

正则表达式:

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.
  }
}

答案 4 :(得分:1)

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();

        }
    }



}

答案 5 :(得分:0)

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

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

答案 6 :(得分:0)

 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;
        }

答案 7 :(得分:0)

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);
        }
    }
}

答案 8 :(得分:-1)

你的循环运行时间太长了。

或者,您可以使用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
        }
}

答案 9 :(得分:-2)

使用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