//两次反转,第一次反转所有的字符都进行反转,第二次在进行单词内部反转从而达到要求
public class 字符串反转单词不反转
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String str = in.nextLine();
System.out.println(reverseSentence(str.toCharArray()));
}
// 反转的方法
private static void reverse(char[] data, int start, int end)
{
if (data == null || data.length < 1 || start < 0 || start > end
|| end > data.length)
{
return;
}
while (start < end)
{
char temp = data[start];
data[start] = data[end];
data[end] = temp;
start++;
end--;
}
}
// 反转整个句子
private static char[] reverseSentence(char[] data)
{
if (data == null || data.length <= 1)
{
return data;
}
// 第一次反转
reverse(data, 0, data.length - 1);
System.out.println(data);
int start = 0, end = 0;
while (start < data.length)
{
if (data[start] == ' ')
{
start++;
end++;
}
else if (end == data.length || data[end] == ' ')
{
reverse(data, start, end - 1);
end++;
start = end;
}
else
{
end++;
}
}
return data;
}
}