简体   繁体   中英

Reversing Arrays, Array.Reverse()

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?

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();

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();

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM