How to check repeated letters in a string c#

67,698

Solution 1

run the loop until repeatedWord.Count()-1

Solution 2

Regular Expression:

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

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

Solution 3

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 Length property.

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

Solution 4

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

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

        }
    }



}
Share:
67,698
MMakati
Author by

MMakati

Updated on July 09, 2022

Comments

  • MMakati
    MMakati almost 2 years

    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.

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

    Any solution for this?

  • Jeroen van Langen
    Jeroen van Langen over 10 years
    You'll miss the last letter?
  • Pierre-Luc Pineault
    Pierre-Luc Pineault over 10 years
    @JeroenvanLangen And you want to check the last letter against what exactly? It will always be different than 'end of line'.
  • dav_i
    dav_i over 10 years
    @JeroenvanLangen new[] { 0, 1, 2 }.Count() == 3
  • Jeroen van Langen
    Jeroen van Langen over 10 years
    True, true, the last letter = [i+1] missed that... ;) i'd rather avoid index+1 in code. will be less readable and forces programmers to use things like count-1 etc. So could cause more "strange" behaviour
  • Michael
    Michael over 10 years
    @I4V You're right. This isn't constrained to sequential repeats.
  • Servy
    Servy over 10 years
    You need to start at the second char if you do this, otherwise you'll fail for looking to the char just before the first.
  • Servy
    Servy over 10 years
    If you do want to solve this problem, rather than the OP's problem, you'll want to use GroupBy and Count. This solution iterates the sequence many times; it's pretty horrible performance wise.
  • Nicholas Carey
    Nicholas Carey over 10 years
    As @Servy said. This, s.GroupBy( c => c ).FirstOrDefault( group => group.Count() > 1 ) != null ; (or something similar) will accomplish the same thing with a lot less work. Your code will run in approximately O(n*^2) time, I believe. O(*mn) actually, with m being the count of distinct characters in the source and n the total number of characters in the source.
  • Michael
    Michael over 10 years
    @NicholasCarey & Servy - agreed.
  • Lakshay Dulani
    Lakshay Dulani about 10 years
    hello timothy! can you please explain how does the code do it
  • Ramu Vemula
    Ramu Vemula about 8 years
    In the count, we can get the repeated characters value
  • Mostafiz
    Mostafiz about 8 years
    better you explain more detail