颠倒“Hello World”的每个单词。 Java的字符串 [英] Reverse each individual word of "Hello World" string with Java

查看:163
本文介绍了颠倒“Hello World”的每个单词。 Java的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要反转Java中String的每个个别字(不是整个字符串,只是每个单词)。

I want to reverse each individual word of a String in Java (not the entire string, just each individual word).

示例:如果输入String为Hello World,则输出应为olleH dlroW。

Example: if input String is "Hello World" then the output should be "olleH dlroW".

推荐答案

这应该可以解决问题。这将迭代源字符串中的每个单词,使用 StringBuilder 的内置 reverse()方法,并输出反转的单词。

This should do the trick. This will iterate through each word in the source string, reverse it using StringBuilder's built-in reverse() method, and output the reversed word.

String source = "Hello World";

for (String part : source.split(" ")) {
    System.out.print(new StringBuilder(part).reverse().toString());
    System.out.print(" ");
}

输出:

olleH dlroW 

注意:评论者正确地指出了我认为应该在这里提到的一些事情。此示例将在结果的末尾附加一个额外的空格。它还假设您的单词每个单独的空格分隔,并且您的句子不包含标点符号。

Notes: Commenters have correctly pointed out a few things that I thought I should mention here. This example will append an extra space to the end of the result. It also assumes your words are separated by a single space each and your sentence contains no punctuation.

这篇关于颠倒“Hello World”的每个单词。 Java的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆