String does not have instance method Reverse
. Your code str.Reverse().ToString()
is actually splitting your string char-by-char and then reversing it using the Reverse
method in the Array
instance.
What you can do is manually split your string into a char array, reverse the array using the Reverse
method in the Array
instance and then join it using the Join
method in String
instance. Something like this:
string str = "hello world";
Console.WriteLine(str.GetType());
// Manually split the string into a char array,
// reverse the array and then join it.
Console.WriteLine("str.ToCharArray().Reverse():");
string NewStr = string.Join("", str.ToCharArray().Reverse());
Console.WriteLine(NewStr);
// Output: "dlrow olleh"
But if you want to stick with the code you wrote then you can do something like this:
string str = "hello world";
Console.WriteLine(str.GetType());
string NewStr = "";
Console.WriteLine("str.Reverse().ToString():");
// Split the string into a char array,
// reverse the char array and append the chars to a new string.
foreach (var i in str.Reverse())
{
NewStr += i.ToString();
}
Console.WriteLine(NewStr);
// Output: "dlrow olleh"
Hope it helped :)