📜  Java中的 StringBuilder setCharAt() 示例

📅  最后修改于: 2022-05-13 01:55:40.081000             🧑  作者: Mango

Java中的 StringBuilder setCharAt() 示例

StringBuilder类的setCharAt(int index, char ch)方法用于设置作为ch传递的位置索引处的字符。此方法将旧序列更改为表示与旧序列相同的新序列,唯一区别是新字符ch 出现在位置索引处。 index 参数必须大于等于 0,并且小于 StringBUilder 对象包含的字符串的长度。
句法:

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 Java, char)