Java中的 StringBuffer reverse() 方法及示例
Java.lang.StringBuffer.reverse() 是一种内置方法,用于反转 StringBuffer 中的字符。该方法使这个字符序列被替换为相反的序列。
句法 :
public StringBuffer reverse()
参数:该方法不带任何参数。
返回值:该方法在反转字符后返回StringBuffer。
例子 :
Input: StringBuffer = GeeksforGeeks
Output = !skeegrofskeeG
Input: StringBuffer = Hello World
Output = !dlroW olleH
下面的程序说明了Java.lang.StringBuffer.reverse() 方法:
方案一:
java
// Java program to illustrate the
// java.lang.StringBuffer.reverse()
import java.lang.*;
public class Test {
public static void main(String args[])
{
StringBuffer sbf = new StringBuffer("Geeksforgeeks!");
System.out.println("String buffer = " + sbf);
// Here it reverses the string buffer
sbf.reverse();
System.out.println("String buffer after reversing = " + sbf);
}
}
java
// Java program to illustrate the
// java.lang.StringBuffer.reverse()
import java.lang.*;
public class Test {
public static void main(String args[])
{
StringBuffer sbf = new StringBuffer("1 2 3 4 5 6 7 8 9 10");
System.out.println("String buffer = " + sbf);
// Here it reverses the string buffer
sbf.reverse();
System.out.println("String buffer after reversing = " + sbf);
}
}
输出:
String buffer = Geeksforgeeks!
String buffer after reversing = !skeegrofskeeG
方案二:
Java
// Java program to illustrate the
// java.lang.StringBuffer.reverse()
import java.lang.*;
public class Test {
public static void main(String args[])
{
StringBuffer sbf = new StringBuffer("1 2 3 4 5 6 7 8 9 10");
System.out.println("String buffer = " + sbf);
// Here it reverses the string buffer
sbf.reverse();
System.out.println("String buffer after reversing = " + sbf);
}
}
输出:
String buffer = 1 2 3 4 5 6 7 8 9 10
String buffer after reversing = 01 9 8 7 6 5 4 3 2 1