这是我使用while循环并获得正确输出的方式:“ dlrow olleh”
static void Main(string[] args)
{
string str = "Hello world";
string reverse = "";
int length = str.Length - 1;
while (length >= 0)
{
reverse = reverse + str[length];
length--;
}
Console.WriteLine(reverse);
Console.ReadKey();
}
但是当我使用具有相同逻辑的for循环时,会得到不同的输出,这对我来说不合适,输出为:“ ddddddddddd”
static void Main(string[] args)
{
string str = "Hello world";
string reverse = "";
int length = str.Length - 1;
for (int i = length; i >= 0; i--)
{
reverse = reverse + str[length];
}
Console.WriteLine(reverse);
Console.ReadKey();
}
答案 0 :(得分:0)
在这里检查此Fiddle
static void Main(string[] args)
{
string str = "Hello world";
string reverse = "";
int length = str.Length;
for (int i = length; i >= 0; i--)
{
reverse = reverse + str[i-1]; // here a change
}
Console.WriteLine(reverse);
Console.ReadKey();
}