Byyo Byyo - 6 months ago 57
C# Question

Find the longest repetition character in String

Let's say i have a string like

string text = "hello dear";

Then I want to determine the longest repetition of coherented characters - in this case it would be
. If there are more than one with the same count, take any.

I have tried to solve this with linq

char rchar = text.GroupBy(y => y).OrderByDescending(y => y.Count()).Select(x => x).First().Key;
int rcount = text.Where(x => x == rchar).Count();
string routput = new string(rchar, rcount);

But this returns
. Am I on the right track?

w.b w.b
Answer Source

Another solution using LINQ:

string text = "hello dear";
string longestRun = new string(text.Select((c, index) => text.Substring(index).TakeWhile(e => e == c))
                                   .OrderByDescending(e => e.Count())

Console.WriteLine(longestRun); // ll

It selects a sequence of substrings starting with the same repeating character, and creates the result string with the longest of them.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download