Search code examples
c#arraysstringreverse

Reverse pre-last element of array


I couldn't found any better way to do it but to split the string into the array:

string str = "unknown printer took a galley of type and scrambled it to make a type specimen book";
string[] split = str.Split(' ');
Console.WriteLine(split[split.Length - 2].Reverse());

The console should return "nemiceps" The code seems right, but there's the wrong output. Any tips?


Solution

  • You need to convert the linq reverse result to an array and pass it to the string constructor like that:

    string word = new string(split[split.Length - 2].Reverse().ToArray());
    
    Console.WriteLine(word);
    

    This convert the IEnumerable<char> to an array and create a new string from this array.