MMakati
MMakati

Reputation: 703

How to check repeated letters in a string c#

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?

Upvotes: 9

Views: 94498

Answers (15)

private string input = "Hi, How are you?";

private List<string>  GetDuplicatedCharacters(string input)
{
    if (string.IsNullOrWhiteSpace(input))
        throw new ArgumentException("Invalid argument, provide a valid input.");

    var duplicatedList = new List<string>();
    var duplicateString = input.ToCharArray().OrderByDescending(x => x.ToString().ToLower()).ToArray();

    int resetCounter = 0;
    int indexCounter = 0;

    for (int i = resetCounter; i < duplicateString.Length; i++)
    {
        i = resetCounter;

        indexCounter = 0;
        
        for (int j = resetCounter; j < duplicateString.Length; j++)
        {
            resetCounter = j;

            if (!char.IsWhiteSpace(duplicateString[i]))
            {
                if (duplicateString[i] == duplicateString[j])
                { indexCounter++; }
                else
                { break; }
            }
        }

        if (!char.IsWhiteSpace(duplicateString[i]))
            duplicatedList.Add(duplicateString[i] + "-" + indexCounter);
    }

    return duplicatedList;
}

Output should looks like:- H - 2 I - 1 O - 2 W - 1 A - 1 R - 1 Y - 1 U - 1 , - 1 ? - 1

Upvotes: 0

Milind Kamble
Milind Kamble

Reputation: 1

using System;
using System.Text;

public class Program
{
    public static void Main(string[] arg)
    {
        StringBuilder message = new StringBuilder("wooooooooooow");
        StringBuilder result = new StringBuilder();
        
        int count = 0;
        message = message.Replace(" ", string.Empty);
        
        while(message.Length > 0)
        {
            for(int i=0; i<message.Length; i++)
            {
                if(message[0] == message[i])
                {
                    count++;
                }
            }
            if(count > 1)
            {
                result = result.Append(message[0]);
            }
            count = 0;
            message = message.Replace(message[0].ToString(), string.Empty);
        }
        Console.WriteLine(result);
    }
}

Upvotes: 0

waris kantroo
waris kantroo

Reputation: 93

I know I am very late to the party, might be of some help to others.

 class Program
{
    static void Main(string[] args)
    {
        // get only duplicates from a string
        string testString = "AABCDEEGTT";
        Dictionary<char, int> duplicates = GetcharCount(testString);
        foreach (var w in duplicates)
        {

            Console.WriteLine(w.Key + "- " + w.Value);

        }
    }

    public static Dictionary<char, int> GetcharCount(string input)
    {
        var charOccurance = new Dictionary<char, int>();
        foreach (var i in input)
        {
            if (charOccurance.ContainsKey(i))
            {

                charOccurance[i]++;
            }

            else
            {
                charOccurance[i] = 1;
            }
        }
        return charOccurance.Where(a => a.Value > 1).ToDictionary(a => a.Key, a => a.Value); // only duolocates not sinlge ones
         //  return charOccurance.ToDictionary(a => a.Key, a => a.Value);
    }
}

Upvotes: 0

Onur Dikmen
Onur Dikmen

Reputation: 367

You can find the first non-repeating number as follows.

    static string intputString = "oossmmaanntuurrkt";
    static void Main(string[] args)
    {

        Console.WriteLine(OutPutValue(intputString));
        Console.ReadLine();
    }

    public static char OutPutValue(string strValue)
    {
        Dictionary<char, int> repeatValue = new Dictionary<char, int>();

        char[] arrValue = intputString.ToCharArray();

        foreach (var item in arrValue)
        {
            int repearCount = 0;
            if (repeatValue.ContainsKey(item))
            {
                repeatValue[item] = repeatValue.FirstOrDefault(t => t.Key == item).Value + 1;
            }
            else
            {
                repearCount++;
                repeatValue.Add(item, repearCount);
            }

        }

        return repeatValue.FirstOrDefault(t => t.Value == 1).Key;
    }

You can get the repeating and how many times information as follows.

repeatValue.Where(t=> t.Value > 1)

Upvotes: 0

pkucas
pkucas

Reputation: 187

You could also do this:

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 will contain your duplicate characters from the original string.

list will contain your original string stripped of duplicates.

Upvotes: 0

Maghalakshmi Saravana
Maghalakshmi Saravana

Reputation: 813

To find duplicate or repeated letters in given string using 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

Upvotes: -2

Srinivas Kondu
Srinivas Kondu

Reputation: 1

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

Upvotes: 0

Debendra Dash
Debendra Dash

Reputation: 5596

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

        }
    }



}

Upvotes: 1

Ramu Vemula
Ramu Vemula

Reputation: 197

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

Upvotes: 0

Michael
Michael

Reputation: 1833

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.

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

Upvotes: -2

Jeroen van Langen
Jeroen van Langen

Reputation: 22038

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

Upvotes: 2

Nicholas Carey
Nicholas Carey

Reputation: 74177

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

Upvotes: 5

KappaG3
KappaG3

Reputation: 671

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

Upvotes: 3

Timothy Shields
Timothy Shields

Reputation: 79441

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.

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

Upvotes: 0

Abdullah Shoaib
Abdullah Shoaib

Reputation: 2095

run the loop until repeatedWord.Count()-1

Upvotes: 13

Related Questions