简体   繁体   中英

Check for repeated character in a string

Check if the input string contains at least one letter that appears twice in a row, like example:

xx,
abcdde (dd),
aabbccdd (aa, bb, cc, or dd),
ugknbfddgicrmopn (double dd).

The below method doesn't work

input.Distinct().Count();

As it return true for awea (repeated a). I only have to check for repeated character continuously.

This will return true if your string contains any multiple chars:

input.Distinct().Count() != input.Length;

You need to check the current and next character index of the input string. Please see sample code below.

        static void Main(string[] args)
    {
        var input = Console.ReadLine();
        var result = HasRepeatedCharacters(input);
        Console.WriteLine(result);
        Console.ReadLine();
    }

    public static bool HasRepeatedCharacters(string input)
    {
        bool hasRepeatedCharacters = false;

        if(input.Length >= 2)
        {
            for (var index = 0; index < input.Length - 1; index++)
            {
                if(input[index] == input[index + 1])
                {
                    hasRepeatedCharacters = true;
                }
            }
        }
        return hasRepeatedCharacters;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM