用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);热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短