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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18133022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:24:06  来源:igfitidea点击:

How to check repeated letters in a string c#

c#stringif-statement

提问by MMakati

I am creating a program that checks repeated letters in a string.

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

For Example:

例如:

wooooooooooow
happpppppppy

呜呜呜
呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜

This is my code:

这是我的代码:

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

The code works but it will always have an error because the last character [i + 1]is empty/null.

该代码有效,但它总是会出错,因为最后一个字符[i + 1]为空/空。

The error is Index was outside the bounds of the array.

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

Any solution for this?

有什么解决办法吗?

采纳答案by Abdullah Shoaib

run the loop until repeatedWord.Count()-1

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

回答by Jeroen van Langen

Just "remember" the last letter i would say.

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

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

回答by Michael

You're running your loop one iteration too long.

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

Alternatively, you could use LINQ to find the unique (distinct) characters in the word, then check their occurrences in the word. If it appears more than once, do something with it.

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

回答by Timothy Shields

You can change your loop condition to have the -1(as others have already pointed out), or you can do it the cool kid way.

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

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

回答by KappaG3

Another option would be using a Regex that matches repeating characters. Then, for each match, you can obtain the number of characters by using the Lengthproperty.

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

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

回答by Nicholas Carey

Regular Expression:

正则表达式:

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

or Linq

或 Linq

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

or roll yer own:

或滚你自己的:

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

Or even

甚至

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

With this last one...

有了这最后一个...

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

or

或者

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

回答by Ramu Vemula

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

回答by Debendra Dash

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

        }
    }



}

回答by Srinivas Kondu

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

回答by Maghalakshmi Saravana

To find duplicate or repeated letters in given string using C#

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

Output:

输出:

e,o,m,r,g

e,o,m,r,g