Reputation:
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?
Upvotes: 1
Views: 1294
Reputation: 37020
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());
Upvotes: 0
Reputation: 26058
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();
Upvotes: 1
Reputation: 101681
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();
Upvotes: 5