Java StringBuilder reverse()方法及实例
StringBuilder的 reverse() 方法用于 逆转StringBuilder中的字符。 该方法有助于将该字符序列替换为该序列的反面。
语法
public java.lang.AbstractStringBuilder reverse()
返回: 该方法在反转字符后返回StringBuilder对象。下面的程序说明了java.lang.StringBuilder.reverse()方法:
示例1 :
// Java program to demonstrate
// the reverse() Method.
class GFG {
public static void main(String[] args)
{
// create a StringBuilder object
// with a String pass as parameter
StringBuilder str
= new StringBuilder("WelcomeGeeks");
// print string
System.out.println("String = "
+ str.toString());
// reverse the string
StringBuilder reverseStr = str.reverse();
// print string
System.out.println("Reverse String = "
+ reverseStr.toString());
}
}
输出
String = WelcomeGeeks
Reverse String = skeeGemocleW
例2 :
// Java program to demonstrate
// the reverse() Method.
class GFG {
public static void main(String[] args)
{
// create a StringBuilder object
// with a String pass as parameter
StringBuilder str
= new StringBuilder("AAAABBBCCCC");
// print string
System.out.println("String = "
+ str.toString());
// reverse the string
StringBuilder reverseStr = str.reverse();
// print string
System.out.println("Reverse String = "
+ reverseStr.toString());
}
}
输出
String = AAAABBBCCCC
Reverse String = CCCCBBBAAAA
参考文献: https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#reverse()