把一个句子中的单词进行反转,例如“how are you",进行反转后”you are how“;
策略:1先将整个句子进行反转
2.分别对每个单词进行反转
package com.luo.stringtest;
public class ReverseString {
public static void main(String[] args) {
String s = "how are you";
String returnS = new ReverseString().swapWords(s);
System.out.println(returnS);
}
public String swapWords(String s){
if(s==null||s.length()==0){
return null;
}
//1.字符串转换为字符数组 chs:how are you
char[] chars = s.toCharArray();
// System.out.println("字符串转换成字符数组:");
// for (char ch:chars){
// System.out.print(ch);
// }
// System.out.println();
//2.对整个字符串进行字符串反转操作
swap(chars,0,chars.length-1);
//3.对单个单词进行反转操作
int begin = 0;
for(int i=0;i<chars.length;i++){
if(chars[i]==' '){
//以空格为分隔符划分单词,对单个单词进行反转
swap(chars,begin,i-1);
begin = i+1;
}
}
//对最后一个单词进行反转
swap(chars,begin,chars.length-1);
//利用String的构造函数将字符数组转换成字符串
return new String(chars);
}
private void swap(char[] chars, int front, int end) {
while (front<end){
char temp = chars[end];
chars [end] = chars[front];
chars[front] = temp;
front++;
end--;
}
// System.out.println("字符数组反转:");
// for (char ch:chars){
// System.out.print(ch);
// }
// System.out.println();
}
}