编写 Java 程序翻转字符串中的每个单词?
java.lang 包中的 StringBuffer 类提供了 reverse() 方法。此方法返回当前字符串中字符的反向序列。使用此方法,你可以反转 Java 中的字符串。
要反转字符串中的每个单词,你需要拆分字符串,将其存储在字符串数组中,并使用 StringBuffer 类的 reverse() 方法反转每个单词。
示例
import java.lang.*; public class StringBufferDemo { public static void main(String[] args) { StringBuffer buff = new StringBuffer("tutorials point"); System.out.println("buffer = " + buff); // reverse characters of the buffer and prints it System.out.println("reverse = " + buff.reverse()); // reverse of the buffer is equivalent to the actual buffer buff = new StringBuffer("malyalam"); System.out.println("buffer = " + buff); // reverse characters of the buffer and prints it System.out.println("reverse = " + buff.reverse()); } }
输出
buffer = tutorials point reverse = tniop slairotut buffer = malyalam reverse = malaylam
广告