企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# Java 程序:反转`String`中的单词 > 原文: [https://beginnersbook.com/2017/09/java-program-to-reverse-words-in-a-string/](https://beginnersbook.com/2017/09/java-program-to-reverse-words-in-a-string/) 该程序反转字符串的每个单词并将反转的字符串显示为输出。例如,如果我们输入一个字符串`"reverse the word of this string"`,那么程序的输出将是:`"esrever eht drow fo siht gnirts"`。 要了解此程序,您应该具有以下 [Java 编程](https://beginnersbook.com/java-tutorial-for-beginners-with-examples/)主题的知识: 1. [Java `for`循环](https://beginnersbook.com/2015/03/for-loop-in-java-with-example/) 2. [Java `String split()`方法](https://beginnersbook.com/2013/12/java-string-split-method-example/) 3. [Java `String charAt()`方法](https://beginnersbook.com/2013/12/java-string-charat-method-example/) ## 示例:使用方法反转`String`中的每个单词 在本程序中,我们首先使用`split()`方法将给定的字符串拆分为子字符串。子串存储在`String`数组`words`中。程序然后使用反向的`for`循环反转子串的每个单词。 ```java public class Example { public void reverseWordInMyString(String str) { /* The split() method of String class splits * a string in several strings based on the * delimiter passed as an argument to it */ String[] words = str.split(" "); String reversedString = ""; for (int i = 0; i < words.length; i++) { String word = words[i]; String reverseWord = ""; for (int j = word.length()-1; j >= 0; j--) { /* The charAt() function returns the character * at the given position in a string */ reverseWord = reverseWord + word.charAt(j); } reversedString = reversedString + reverseWord + " "; } System.out.println(str); System.out.println(reversedString); } public static void main(String[] args) { Example obj = new Example(); obj.reverseWordInMyString("Welcome to BeginnersBook"); obj.reverseWordInMyString("This is an easy Java Program"); } } ``` **输出:** ```java Welcome to BeginnersBook emocleW ot kooBsrennigeB This is an easy Java Program sihT si na ysae avaJ margorP ``` 看看这些相关的 [java 程序](https://beginnersbook.com/2017/09/java-examples/): 1. [Java 程序:反转数字](https://beginnersbook.com/2014/01/java-program-to-reverse-a-number/) 2. [Java 程序:反转字符串](https://beginnersbook.com/2017/09/java-program-to-reverse-a-string-using-recursion/) 3. [Java 程序:反转数组](https://beginnersbook.com/2017/09/java-program-to-reverse-the-array/) 4. [Java 程序:使用循环检查 Palindrome 字符串](https://beginnersbook.com/2014/01/java-program-to-check-palindrome-string/)