17

I'm solving a coding challenge on Coderbyte with C# using lists. I have the desired outcome but need to return it as a string.

I would like to know how to convert my list of chars into a string. Thank you in advance.

Here's my code:

string s = "I love dogs";
int i, j = 0;
List<char> array1 = new List<char>();
List<char> array2 = new List<char>();

for (i = 0; i < s.Length; i++)
{
    if (s.Length == j)
        break;

    if (Char.IsLetter(s[i]))
    {
        array1.Add(s[i]);
    }
    else
    {
        for (j = i; j < s.Length; j++)
        {
            if (Char.IsLetter(s[j]))
            {
                array2.Add(s[i]);
            }
            if (!Char.IsLetter(s[j]) || j == s.Length - 1)
            {
                if (array1.Count >= array2.Count)
                {
                    array2.Clear();
                }
                else
                {
                    array1.Clear();
                    array1.AddRange(array2);
                    array2.Clear();
                }
            }
        }
    }
} // How to convert array1 into String ?
elmer007
  • 1,412
  • 14
  • 27
Bennity
  • 213
  • 1
  • 3
  • 10
  • 5
    `string result = new string(array1.ToArray());` – René Vogt Oct 23 '19 at 13:42
  • 4
    While you *could* keep them as lists, I'd suggest using `StringBuilder` instead of `List`. As far as I can see, everything you're doing with the lists, you could do with `StringBuilder` instead. Then just call `ToString` at the end. – Jon Skeet Oct 23 '19 at 13:43
  • @René Vogt this has worked thank you very much! – Bennity Oct 23 '19 at 13:49
  • @Jon Skeet will consider StringBuilder next time :)! – Bennity Oct 23 '19 at 13:50
  • Any reason for not changing to use it right now? It's designed for precisely this sort of task. Unless this is really throw-away code, I'd say that using StringBuilder is significantly more idiomatic. – Jon Skeet Oct 23 '19 at 13:59

1 Answers1

47

One option for this is to use the string constructor:

var myString = new string(array1.ToArray());
haldo
  • 14,512
  • 5
  • 46
  • 52