應用java完成單詞倒序分列。本站提示廣大學習愛好者:(應用java完成單詞倒序分列)文章只能為提供參考,不一定能成為您想要的結果。以下是應用java完成單詞倒序分列正文
本文就是會將數組外面的單詞停止倒序分列 例如 how old are you -> you are old how
示例法式輸入成果:
the first:
How old are you !? I don't understand
the second:
understand don't I ?! you are old How
示例代碼
public static void main(String[] args) {
char[] chars= new String("How old are you !? I don't understand").toCharArray();
System.out.println("the first:");
System.out.println(chars);
reverseWords(chars); //重要辦法
System.out.println("the second:");
System.out.println(chars);
}
/**
* 會將數組外面的單詞 倒序分列 例如 how old are you -> you are old how
* @param chars
*/
public static void reverseWords(char[] chars) {
reverseChars(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){
reverseChars(chars,begin,end);
}
}
}else{
if(begin!=-1){
reverseChars(chars,begin,end);
begin=-1;
end=0;
}
}
}
}
/**
* 將char 必定規模內的 字符 倒序分列 例如 hello -> olleh
* @param chars 數組
* @param begin 開端地位
* @param end 停止地位
*/
public static void reverseChars(char[] chars, int begin, int end) {
while(end>begin){
char c = chars[begin];
chars[begin] = chars[end];
chars[end] = c;
begin++;
end--;
}
}
以上就是應用java完成單詞倒序分列,願望對年夜家可以或許懂得,對年夜家有所贊助