字符串中的单词反转
写⼀个函数,将⼀个字符串中的单词反转过来,单词的定义是:完全由字⺟组成且由空
格分开的字符串。例如下⾯的字符串:“ a hello1 abc good!”,其中“a”和“abc”是单词,
⽽“hello1”和“good!”不是单词(原因是这两个字符串中包含⾮字⺟的字符1和!)。
反转过来的结果就是“ a hello1 cba good!”
public class Demo{
public static void main(String args[]){
String s = "a hello1 abc good!";
String string = method(s);
System.out.println(string);
}
public static String method(String s) {
String[] words = s.split(" ");
String str = "";
/* ^开头 $结尾 +一次或者多次*/
String reg = "[a-zA-Z]+";
for (String word : words) {
if (Pattern.matches(reg, word)) {
StringBuilder sb = new StringBuilder(word);
sb.reverse();
str += sb + " ";
} else {
str += word + " ";
}
}
return str;
}
}