单词翻转
在输入一个英文句子,翻转句子中的单词的顺序。要求单词内字符的顺序不变,句子中单词以空格符隔开。为简单起见,标点符号和普通字母处理一样。例如“I am a student.”,则输出“student. a am I”。
想法:
由特殊到一般:把每一个单词当作一个字母的形式,如I=A ,B=am,C=a, D=student.。本体相当于把char s[]={‘A’,’B’,’C’,’D’}进行翻转。
例如:把英文句子存入字符串数组。代码如下所示:
public class wordReverse {
public static void main(String[] args) {
String s[]={"you ","must ","do ","it ","right ","now."};
System.out.println(s[1]);
int length=s.length;
s=ReverseString(s,0,length-1);
StringBuilder str= new StringBuilder();
str.append(s[0]+s[1]+s[2]+s[3]+s[4]+s[5]);
String str1=str.toString();
str1=str1.trim();
System.out.println(str1);
}
/**
* 反转数组中,从from下标开始到to下标结束的字符
* @param s
* @param from
* @param to
* @return
*/
public static String[] ReverseString(String s[],int from ,int to){
while(from<to){
String t=s[from];
s[from++]=s[to];
s[to--]=t;
}
return s;
}
}
如果想从控制台输入句子那么首先得知道怎么实现控制台输入,控制台输入的方法如下:
String s1[] =new String[100];
BufferedReader inputSteam=new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入一个英文句子");
try {
String strBuffer=inputSteam.readLine();
strBuffer=strBuffer.trim();
s1=strBuffer.split(" ");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
完整代码如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class wordReverse {
public static void main(String[] args) {
String s1[] =new String[100];
BufferedReader inputSteam=new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入一个英文句子");
try {
String strBuffer=inputSteam.readLine();
strBuffer=strBuffer.trim();
s1=strBuffer.split(" ");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int length=s1.length-1;
for(int k=0;k<length;k++){
StringBuffer sB=new StringBuffer();
sB.append(s1[k]+" ");
s1[k]=sB.toString();
//System.out.print(sB.toString());
}
String s[]=ReverseString(s1,0,s1.length-1);
for(int j=0;j<s.length;j++){
System.out.print(s[j]);
}
}
/**
* 反转数组中,从from下标开始到to下标结束的字符
* @param s
* @param from
* @param to
* @return
*/
public static String[] ReverseString(String s[],int from ,int to){
while(from<to){
String t=s[from];
s[from++]=s[to];
s[to--]=t;
}
return s;
}
}