9

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?

5
  • 10
    repeatedWord.Count() - 1 Commented Aug 8, 2013 at 18:10
  • It is pretty clear: you cannot iterate until the last position if you look for +1 index. repeatedWord.Count() - 1 should be the maximum value. Commented Aug 8, 2013 at 18:10
  • If you have an array that is 10 elements long, you can't attempt to read the 11th element. Have you stepped through your 'for' loop in a debugger to see what's happening? Commented Aug 8, 2013 at 18:11
  • Are you looking for sequential repetition or any character repetition in the entire string? Also are you interested to know the actual character which is repeated, or just want a bool result? Commented Aug 8, 2013 at 18:35
  • What is your goal? Do you want to get the number of repeated characters? It is not clear that what your objective is. Commented Aug 26, 2014 at 3:54

15 Answers 15

13

run the loop until repeatedWord.Count()-1

Sign up to request clarification or add additional context in comments.

5 Comments

You'll miss the last letter?
@JeroenvanLangen And you want to check the last letter against what exactly? It will always be different than 'end of line'.
@JeroenvanLangen new[] { 0, 1, 2 }.Count() == 3
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
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.
5

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

Comments

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

Comments

2

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

Comments

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

        }
    }



}

Comments

0

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

1 Comment

hello timothy! can you please explain how does the code do it
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;
        }

2 Comments

In the count, we can get the repeated characters value
better you explain more detail
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);
        }
    }
}

Comments

0

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.

Comments

0

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)

Comments

0

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

Comments

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

1 Comment

Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, can you edit your answer to include an explanation of what you're doing and why you believe it is the best approach?
0
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

Comments

-2

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

4 Comments

@I4V You're right. This isn't constrained to sequential repeats.
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.
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.
@NicholasCarey & Servy - agreed.
-2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.