java實現字串中的單詞分別反轉,如how are you ?==>ohw rae oyu ?
阿新 • • 發佈:2018-12-26
保持單詞之間的空格位數不變,而不是簡單的分割字串後再分別反轉
public class MyReverseWords {
public static void main(String[] args) {
String str = "how are you ? ";
char[] chars = str.toCharArray();
reverseWords(chars);
System.out.println(new String(chars));
}
/**
* 將字元陣列的單詞分別反轉,並保持空格間距不變
* 如how are you ?==>ohw rae oyu ?
* @param chars
*/
public static void reverseWords(char[] chars) {
int begin = -1;
int end = 0;
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (c != ' ') {//判斷是否為單詞,如果是,則標記
if(begin == -1){
begin = i;
end = i;
}else {
end = i;
reverseChars(chars, begin, end);
}
}else{
//一個單詞結束,進行反轉操作
if(begin != -1){
reverseChars(chars, begin, end);
}
begin=-1;
//end = 0;
}
}
}
/**
* 反轉字元陣列的指定範圍
* @param chars
* @param begin
* @param end
*/
public static void reverseChars(char[] chars , int begin , int end){
while(begin < end){
char swap = chars[begin];
chars[begin] = chars[end];
chars[end] = swap;
begin++;
end--;
}
}
}