【Java】【字符串】按照单词翻转字符串
原创
©著作权归作者所有:来自51CTO博客作者wx5cee84fb43fbb的原创作品,请联系作者获取转载授权,否则将追究法律责任
问题描述: 将 here you are 翻转为 are you here
思路:
先将字符串整体翻转,然后把字符串按照空格隔开,将每个单词分别再次翻转。
代码如下:
public static void main(String[] args) {
String string = "here you are";
//先把所有的字符串翻转
String result = reverse(string);
System.out.println(result);
}
static String reverse(String string){
StringBuilder stringBuilder2 = new StringBuilder();
String string2 = reverseString(string);
String[] words = string2.split(" ");
for (int i = 0; i < words.length; i++) {
stringBuilder2.append(reverseString(words[i])+" ");
}
return stringBuilder2.deleteCharAt(stringBuilder2.length()-1).toString();
}
static String reverseString(String string){
StringBuilder stringBuilder = new StringBuilder(string);
return stringBuilder.reverse().toString();
}