比如:
输入字符串: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--;
}
}
}