反转英文句子内单词

比如:

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值