How to check repeated letters in a string c#

前端 未结 10 563
太阳男子
太阳男子 2020-12-21 01:39

I am creating a program that checks repeated letters in a string.

For Example:

wooooooooooow
happpppppppy

This is my

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-21 01:43

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

提交回复
热议问题