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


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


StringBuilder類的setCharAt(int index,char ch)方法用於將字符設置為作為ch傳遞的位置索引。該方法將舊序列更改為代表一個新序列,該新序列與舊序列相同,隻是區別在於位置索引處存在新字符ch。 index參數必須大於或等於0,並且小於StringBUilder對象包含的String的長度。
用法:

public void setCharAt(int index, char ch)

參數:
此方法接受兩個參數:

  1. index–整數類型值,表示要設置的字符的索引。
  2. ch–引用新字符的字符類型值。

返回值:
此方法不返回任何內容。
異常:
如果索引為負,大於length(),則IndexOutOfBoundsException。


以下程序說明了java.lang.StringBuilder.setCharAt()方法:
示例1:

// Java program to demonstrate 
// the setCharAt() 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()); 
  
        // set char at index 2 to 'L' 
        str.setCharAt(2, 'L'); 
  
        // print string 
        System.out.println("After setCharAt() String = "
                           + str.toString()); 
    } 
}

輸出:

String = WelcomeGeeks
After setCharAt() String = WeLcomeGeeks

示例2:

// Java program to demonstrate 
// the setCharAt() Method. 
  
class GFG { 
    public static void main(String[] args) 
    { 
  
        // create a StringBuilder object 
        // with a String pass as parameter 
        StringBuilder str 
            = new StringBuilder("Tony Stark will die"); 
  
        // print string 
        System.out.println("String = "
                           + str.toString()); 
  
        // set char at index 9 to '1' 
        str.setCharAt(9, '1'); 
  
        // print string 
        System.out.println("After setCharAt() String = "
                           + str.toString()); 
    } 
}

輸出:

String = Tony Stark will die
After setCharAt() String = Tony Star1 will die

示例3:傳遞負索引時:

// Java program to demonstrate 
// Exception thrown by the setCharAt() Method. 
  
class GFG { 
    public static void main(String[] args) 
    { 
  
        // create a StringBuilder object 
        // with a String pass as parameter 
        StringBuilder str 
            = new StringBuilder("Tony Stark"); 
  
        try { 
            // pass  index -15 
            str.setCharAt(-15, 'A'); 
        } 
        catch (Exception e) { 
  
            e.printStackTrace(); 
        } 
    } 
}

輸出:

java.lang.StringIndexOutOfBoundsException: String index out of range: -15
    at java.lang.AbstractStringBuilder.setCharAt(AbstractStringBuilder.java:407)
    at java.lang.StringBuilder.setCharAt(StringBuilder.java:76)
    at GFG.main(File.java:16)

參考文獻:
https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#setCharAt(int,char)



相關用法


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