當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java StringBuilder reverse()用法及代碼示例


StringBuilder的reverse()方法用於反轉StringBuilder中的字符。該方法有助於將此字符序列替換為相反的序列。

用法:

public java.lang.AbstractStringBuilder reverse()

返回值:
反轉字符後,此方法返回StringBuilder對象。


以下程序說明了java.lang.StringBuilder.replace()方法:
示例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

參考文獻:



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 StringBuilder reverse() in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。