1. 程式人生 > >java將字串進行反轉單詞需正確拼寫

java將字串進行反轉單詞需正確拼寫

/**
 * 將字串進行反轉,必須保證單詞的正確拼寫
 * @author Administrator
 *
 */
public class TestReserves {
public static void main(String[] args) {
String str = "How are you ?!    I'm fine! ";
char[] chars = str.toCharArray();
System.out.println(chars);


resverseStr(chars);
System.out.println(chars);
}


/**
* 轉換字串
* @param chars
*/
public static void resverseStr(char[] chars) {
// 先將字串進行完全反轉  !enif m'I    !? uoy era woH
resverseWord(chars, 0, chars.length - 1);
int begin = -1;
int end = 0;
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '\'') {
if (begin == -1) {
begin = i;
end = i;
} else {
end = i;
if (i == chars.length - 1) {
resverseWord(chars, begin, end);
}
}


} else {
if (begin != -1) {
resverseWord(chars, begin, end);
begin = -1;
end = 0;
}
}
}
}


/**
* 將char陣列指定位置的資料進行反轉
* @param chars 要反轉的char陣列
* @param begin 開始位置
* @param end 結束位置 
*/
public static void resverseWord(char[] chars, int begin, int end) {
while (end > begin) {
char c = chars[begin];
chars[begin] = chars[end];
chars[end] = c;
begin++;
end--;
}
}
}