s = "I am a student"
Return "student a am I"
将每个单词翻转,然后将整个字符串翻转。
public static void Reverse(char[] array, int start, int end)
{
if (array == null || start < 0 || end > array.Length - 1)
{
return;
}
while (start < end)
{
char temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}
public static string ReverseSentense(string sentense)
{
if (string.IsNullOrEmpty(sentense))
{
return null;
}
char[] array = sentense.ToCharArray();
int start = 0;
int end = array.Length - 1;
// Step1.先翻转整个句子
Reverse(array, start, end);
// Step2.再翻转句中的每个单词
start = end = 0;
while (start < array.Length)
{
if (array[start] == ' ')//此时一定是else if调用之后的start == end
{
start++;
end++;
} //end等于尾部或者等于空 那久可以翻转切改变start和end
else if (end == array.Length || array[end] == ' ')
{
Reverse(array, start, --end);
start = end + 1;
end++;
}
else
{ //就是单个单词内部的情况
end++;
}
}
return new string(array);
}