比如:
輸入字符串:Hello, I need an apple.
輸出結果爲:olleH, I deen na elppa.
注:只反轉句子中各單詞,遇到不是英文字符的字符則視爲單詞的結束。
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s="";
while((s=br.readLine())!=null){
char[] ch=s.toCharArray();
int begin=-1;
int end=-1;
for(int i=0;i<ch.length;i++){
if(!is_alf(ch[i])){//若不是英文字符
if(begin!=-1){//之前是英文單詞
reverse(ch,begin,end);
}//之前不是英文單詞,跳過
begin=-1;
}else{//是英文字符
if(begin == -1){
begin=i;//若begin爲1,則begin賦值
end=begin;
}else{
end++;//end遞增
}
}
}
//若最後是英文單詞結束,則還要單獨reverse
if(begin!=-1){
reverse(ch,begin,end);
}
//
System.out.println(String.valueOf(ch));
}
}
public static boolean is_alf(char c){
if(c>='a'&&c<='z'||c>='A'&&c<='Z'){
return true;
}else{
return false;
}
}
public static void reverse(char[] ch,int begin,int end){
while(begin < end){
char temp=ch[begin];
ch[begin]=ch[end];
ch[end]=temp;
begin++;
end--;
}
}
}