7

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

例如:

呜呜呜
呜呜呜呜呜呜呜呜

这是我的代码:

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

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

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

有什么解决办法吗?

4

11 回答 11

10

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

于 2013-08-08T18:11:01.733 回答
4

正则表达式:

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.
  }
}
于 2013-08-08T19:49:28.210 回答
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();
于 2013-08-08T18:21:22.760 回答
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];
}
于 2013-08-08T18:11:48.917 回答
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();

        }
    }



}
于 2018-01-15T06:39:50.020 回答
0

您可以将循环条件更改为具有-1(正如其他人已经指出的那样),或者您可以以酷孩子的方式进行。

var text = "wooooooooooow happpppppppy";
var repeats = text.Zip(text.Skip(1), (a, b) => a == b).Count(x => x);
于 2013-08-08T18:20:44.433 回答
0

你也可以这样做:

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将包含删除重复项的原始字符串。

于 2022-02-17T19:04:03.917 回答
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;
        }
于 2016-04-25T11:34:43.797 回答
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);
        }
    }
}
于 2019-07-29T15:18:50.807 回答
-2

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

或者,您可以使用 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
        }
}
于 2013-08-08T18:14:06.773 回答
-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

于 2020-02-25T10:25:19.793 回答