以单词为单位对字符串进行翻转(用C#编写,但不用其中的库函数)
//以单词为单位对字符串进行翻转,先按照字母进行翻转,然后按照单词进行翻转
string str1 = "12345 67890";
string str2 = "";
string str3 = "";
for (int o = str1.Length - 1; o >= 0; o--)
str2 += str1[o];//按字母翻转
char[] chArr = new char[str1.Length];
int i = 0;
int j = 0;
int index = 0;
while (index < str2.Length-1)
{
if (str2[index] == ' ')
{
j = index - 1;
while (i <= j)
{
chArr[i] = str2[j];
chArr[j] = str2[i];
i++;
j--;
}
index++;
i = index;
}
else
{
index++;
}
}
if (index == str2.Length - 1)
{
j = index;
while (i <= j)
{
chArr[i] = str2[j];
chArr[j] = str2[i];
i++;
j--;
}
}
for (int k = 0; k < str2.Length; k++)
str3 += chArr[k].ToString();//按照单词翻转
Console.WriteLine("The reverse letter by letter of {0} is {1}", str1, str2);
Console.WriteLine("The reverse word by word of {0} is {1}", str1, str3);
Console.ReadLine();