package oj.test;
import java.util.*;
public class CDemo1 {
/**
* 通过输入英文句子,将每个单词反过来,标点符号顺序不变。非26个字母且非标点符号的情况即可标识单词结束。
* 标点符号包括,.!?
输入:Hello, I need an apple.
输出:olleH, I deen na elppa.
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String output = fun(input);
sop(output);
}
private static String fun(String str) {
char[] chs = str.toCharArray();
char[] result = new char[chs.length];
int j=0;
String s1 = str;
for(int i=0;i<chs.length;i++){
if(chs[i]==',' || chs[i]=='.' || chs[i]=='!' || chs[i]=='?' || chs[i]==' ' ){
if(chs[i-1]==',' || chs[i-1]=='.' || chs[i-1]=='!' || chs[i-1]=='?' || chs[i-1]==' '){
result[i] = chs[i];
j=i+1;
continue;
}
result[i] = chs[i];
String temp = s1.substring(j, i);
reverse(temp,result,j);
j=i+1;
}
}
return new String(result);
}
private static void reverse(String temp, char[] result, int j) {
char[] t = temp.toCharArray();
for(int x=0,y=t.length-1;x<y;x++,y--){
char lin = t[x];
t[x] = t[y];
t[y] = lin;
}
//sop("单个单词反转后的temp:"+new String(t));
for(int x=0;x<t.length;x++){
result[j+x] = t[x];
}
//sop("result:"+new String(result));
}
private static void sop(Object obj) {
System.out.println(obj);
}
}
本文介绍了一个Java程序,该程序能够接收英文句子作为输入,并实现每个单词字符的翻转,同时保持标点符号的位置不变。通过示例代码详细展示了如何定义和实现这一功能。
5066

被折叠的 条评论
为什么被折叠?



