用Java反转给定字符串中的单词
字符串中单词的顺序可以颠倒,以单词相反的顺序显示字符串。一个例子如下。
String = I love mangoes Reversed string = mangoes love I
演示该程序的程序如下。
示例
import java.util.regex.Pattern; public class Example { public static void main(String[] args) { String str = "the sky is blue"; Pattern p = Pattern.compile("\\s"); System.out.println("The original string is: " + str); String[] temp = p.split(str); String rev = ""; for (int i = 0; i < temp.length; i++) { if (i == temp.length - 1) rev = temp[i] + rev; else rev = " " + temp[i] + rev; } System.out.println("The reversed string is: " + rev); } }
输出结果
The original string is: the sky is blue The reversed string is: blue is sky the
现在让我们了解上面的程序。
首先打印原始字符串。存在空格字符时,将字符串拆分并存储在数组temp中。演示此过程的代码段如下所示。
String str = "the sky is blue"; Pattern p = Pattern.compile("\\s"); System.out.println("The original string is: " + str); String[] temp = p.split(str); String rev = "";
然后通过循环遍历字符串temp,使用for循环以相反的顺序将字符串存储在字符串rev中。最终显示rev。证明这一点的代码片段如下所示-
for (int i = 0; i < temp.length; i++) { if (i == temp.length - 1) rev = temp[i] + rev; else rev = " " + temp[i] + rev; } System.out.println("The reversed string is: " + rev);