1

I have the following code to reverse a string:

Console.Title = "*****Reverse a String*****";
Console.WriteLine("*****Reverse a String*****");
Console.WriteLine("=> Enter the text to be reversed:");
string input = Console.ReadLine();
Console.WriteLine("=> Reversing...");
char[] arrInput = input.ToCharArray();
Array.Reverse(arrInput);
String final = new String(arrInput);
Console.WriteLine("=> {0}", final);
Console.WriteLine("=> Press any key to terminate.");
Console.ReadKey();

Array.Reverse(arrInput) works but arrInput.Reverse() doesnt! Any pointers?

0

3 Answers 3

5

arrInput.Reverse uses LINQ Reverse method which doesn't change the original collection. You need to call ToArray on it

var reversed = arrInput.Reverse().ToArray();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Will select as answer when it lets me!
1

arrInput.Reverse() returns an enumerable:

IEnumerable<char> inputEnumerable = arrInput.Reverse();

Also as Selman22 points out, Reverse() is going to return an IEnumerable not an array, so you'll also have to add ToArray() if you want to use the original variable:

arrInput = arrInput.Reverse().ToArray();

1 Comment

@Selman22 Good point, I was thinking the array could hold an IEnumerable for some reason
0

You don't have to explicitly create an array to use the Reverse method; you could just do this:

// Get string from user as you're already doing
string input = Console.ReadLine();

// Reverse it and assign to new string
string reversed = new string(input.Reverse().ToArray());

In other words, this code:

string input = Console.ReadLine();
Console.WriteLine("=> Reversing...");
char[] arrInput = input.ToCharArray();
Array.Reverse(arrInput);
String final = new String(arrInput);

Can be simplified to:

string input = Console.ReadLine();
Console.WriteLine("=> Reversing...");
String final = new String(input.Reverse().ToArray());

3 Comments

Wouldn't .ToArray() make it an array which would make it an array when reversed is a string?
@LukeParker Not really; Reverse is called first, which returns an IEnumerable<char>. The ToArray() call is needed to convert the IEnumerable to an Array type for the string constructor. But you can call Reverse on a string without converting it to an Array, like: var reversed = "some String".Reverse();. Just as you can grab a character from a string using an index without explicitly converting it to an array: char fourthCharacter = "someString"[3];
Updated answer with how the explicit array declaration can be removed, hope that helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.