java.lang包的StringBuffer 类提供了reverse()方法。此方法返回当前String中字符的相反顺序。使用此方法,可以在Java中反转字符串。
要反转字符串中的每个单词,您需要分割字符串,将其存储在字符串数组中,然后使用StringBuffer类的reverse() 方法反转每个单词。
import java.lang.*; public class StringBufferDemo { public static void main(String[] args) { StringBuffer buff = new StringBuffer("nhooo.com"); System.out.println("buffer = " + buff); //反转缓冲区的字符并打印 System.out.println("reverse = " + buff.reverse()); //缓冲区的反向等效于实际缓冲区 buff = new StringBuffer("malyalam"); System.out.println("buffer = " + buff); //反转缓冲区的字符并打印 System.out.println("reverse = " + buff.reverse()); } }
输出结果
buffer = nhooo.com reverse = tniop slairotut buffer = malyalam reverse = malaylam