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(" ");
}
Output:
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…