Arrays are zero-based; by starting with
i = 1
you skip one element. And by using
c.Length - 1
, you also skip the last element. You also don't need to store the whole list, you can store only the longest. It's also better to use
StringBuilder
than string concatenation. And the
temp = next.ToString();
line shouldn't be there, because it causes a char to be counted twice.
char[] c = input.ToCharArray();
string longest = "";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < c.Length; i++)
{
char curr = c[i];
char next = i != c.Length - 1 ? c[i + 1] : '\0';
sb.Append(curr);
if (curr != next)
{
string temp = sb.ToString();
if (temp.Length > longest.Length)
{
longest = temp;
}
sb.Clear();
}
}
Console.WriteLine(longest[0]);
Console.WriteLine("Press any key...");
Console.ReadKey();
The above code shows how you can do it with a
StringBuilder
and without LINQ.
Why StringBuilder? Take a look at this article:
http://yoda.arachsys.com/csharp/stringbuilder.html[
^]
Quote:
Definitely use StringBuilder when you're concatenating in a non-trivial loop - especially if you don't know for sure (at compile time) how many iterations you'll make through the loop. For example, reading a file a character at a time, building up a string as you go using the += operator is potentially performance suicide.
That is the case here; we don't know how many iterations it'll make, because that depends on the input.