原文: 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 编程主题的知识:

  1. Java for循环
  2. Java String split()方法
  3. Java String charAt()方法

示例:使用方法反转String中的每个单词

在本程序中,我们首先使用split()方法将给定的字符串拆分为子字符串。子串存储在String数组words中。程序然后使用反向的for循环反转子串的每个单词。

  1. public class Example
  2. {
  3. public void reverseWordInMyString(String str)
  4. {
  5. /* The split() method of String class splits
  6. * a string in several strings based on the
  7. * delimiter passed as an argument to it
  8. */
  9. String[] words = str.split(" ");
  10. String reversedString = "";
  11. for (int i = 0; i < words.length; i++)
  12. {
  13. String word = words[i];
  14. String reverseWord = "";
  15. for (int j = word.length()-1; j >= 0; j--)
  16. {
  17. /* The charAt() function returns the character
  18. * at the given position in a string
  19. */
  20. reverseWord = reverseWord + word.charAt(j);
  21. }
  22. reversedString = reversedString + reverseWord + " ";
  23. }
  24. System.out.println(str);
  25. System.out.println(reversedString);
  26. }
  27. public static void main(String[] args)
  28. {
  29. Example obj = new Example();
  30. obj.reverseWordInMyString("Welcome to BeginnersBook");
  31. obj.reverseWordInMyString("This is an easy Java Program");
  32. }
  33. }

输出:

  1. Welcome to BeginnersBook
  2. emocleW ot kooBsrennigeB
  3. This is an easy Java Program
  4. sihT si na ysae avaJ margorP

看看这些相关的 java 程序

  1. Java 程序:反转数字
  2. Java 程序:反转字符串
  3. Java 程序:反转数组
  4. Java 程序:使用循环检查 Palindrome 字符串