a quite simple code:
string str = "hello world";
Console.WriteLine(str.GetType());
Console.WriteLine("str.Reverse().ToString():");
Console.WriteLine(str.Reverse().ToString());
and got the following output:
System.String str.Reverse().ToString(): System.Linq.Enumerable ReverseIterator`1[System.Char]
the question is , why there is the 'ReverseIterator`1' error ? thanks.
CodePudding user response:
String does not have instance method Reverse, it is actually an extension method Enumerable.Reverse<TSource>(IEnumerable<TSource>) available on string due to the fact that it implements IEnumerable<char>:
public sealed class String : ICloneable,
IComparable,
IComparable<string>,
IConvertible,
IEquatable<string>,
System.Collections.Generic.IEnumerable<char>
Reverse returns IEnumerable<char> with underlying implementation missing overload for ToString so it outputs type name. I.e. next to lines will have the same output:
Console.WriteLine(str.Reverse().ToString());
Console.WriteLine(str.Reverse().GetType());
You can reverse string next "quick and dirty" solution:
var reversed = new string(str.Reverse().ToArray());
Or select one of answers provided here.
CodePudding user response:
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 :)
