反转“Hello World"的每个单词字符串与 Java [英] Reverse each individual word of "Hello World" string with Java

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

问题描述

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

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

示例:如果输入字符串是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天全站免登陆