1实现句子的反转,如:hello world 变成world hello
直接上代码(重点是媲美split(" ")函数的部分):
import java.util.*;
import java.io.*;
//句子反转
public class Test {
public static String reverse(String s) { //静态函数包装反转功能
List<String> ls = new ArrayList<String>(); //泛型构造String类型的list对象
int i = 0,j=1;
//每碰到一个空格,截取字符串
for(j=1; j<s.length();j++) {
if(s.charAt(j) == ' ') {
String a = s.substring(i,j);
j++;
ls.add(a);
i = j;
}
//最后一个单词需要额外判断
if(j == s.length()-1) {
String b = s.substring(i,j+1);
ls.add(b);
}
}
Collections.reverse(ls); //调用静态类Collections.sort()现成的反转
StringBuffer br = new StringBuffer();
for(Object o:ls) {
br.append(o + " ");
}
s = br.toString();
return s;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String[] arr = new String[10];
int i = 0;
while(sc.hasNextLine()) {
arr[i] = new String(sc.nextLine());
i++;
}
int count = i;
for(i=0; i<count;i++) {
arr[i] = Test.reverse(arr[i]);
System.out.println(arr[i].trim()); //注意反转之后开头是有空格的,需要去掉
}
}
}