算法思想:
(1)从字符串最后一个字符开始向前查找,遇到第一个空白字符结束查找,用变量curPos记录当前位置,查找过程中用变量wordLength记录单词长度,以curPos和wordLength为依据保存单词到字符数组result中。
(2)以curPos为依据向前查找空白,遇到第一个非空白字符结束查找,用变量curPos记录当前位置,查找过程中用变量spaceLength记录单词长度,以curPos和spaceLength为依据保存单词到字符数组result中。
(3)判断curPos值,如果大于等于0,重复(1)(2)两步。放到do..while循环中
(1)(2)两步可以颠倒。因为字符串最后可能是空白"I am a student "也可能是非空白" I am a student"
输入字符串:"I am a student"结果" student a am I".可以测试字符串的其他结构。如空白字符串,一个单词,开始为空白,最后为空白,单词间任意个空白。结果都正确。具体代码如下:
-----------------------------------------------------------------------------------------------------------------------------------
static void Main(string[] args)
{
string str = "";
Program.ReverseStringByWordUnit(str);
}
static void ReverseStringByWordUnit(string orgString)
{
int totalLength = orgString.Length;
if (0 >= totalLength)
{
Console.WriteLine("字符串为空,请输入一个长度大于0的字符串!");
return;
}
char[] result = new char[totalLength];//保存结果的字符数组
int wordLength = 0;//单词长度
int spaceLength = 0;//空白长度
int index = 0;//记录保存结果到result字符数组的下标
int curPos = totalLength - 1;//记录开始索引字符串的位置,初始为字符串最后一个字符。
do
{
int i;
//从字符串最后一个位置开始向前查找,遇到第一个空白,结束查找。
for (i = curPos; i >= 0; )
{
if (orgString[i] != ' ' && orgString[i] != '/t')
{
i--;
wordLength++;
continue;
}
else
break;
}
//保存当前索引位置,作为输出单词的起始位置依据以及查找空白的开始位置依据
curPos = i;
//从单词的开始位置保存该单词的每个字母到result字符数组里
for (int j = curPos + 1; j <= curPos + wordLength; j++)
{
result[index] = orgString[j];
index++;
}
//查找两个单词间的空白
for (i = curPos; i >= 0; )
{
if (orgString[i] == ' ' || orgString[i] == '/t')
{
i--;
spaceLength++;
continue;
}
else
break;
}
//保存当前索引位置,作为输出空白的起始位置依据以及查找下一个单词的开始位置依据
curPos = i;
//保存空白字符到字符数组里
for (int j = curPos + 1; j <= curPos + spaceLength; j++)
{
result[index] = orgString[j];
index++;
}
//置单词长度变量和空白长度变量为0
wordLength = 0;
spaceLength = 0;
} while (curPos >= 0);
//输出结果
for (int i = 0; i < totalLength; i++)
Console.Write("{0}", result[i]);
Console.WriteLine();
}