Java StringBuffer setCharAt()方法及示例
StringBuffer类的 setCharAt() 方法将位置索引处的字符设置为作为参数传递给方法的字符值。该方法返回一个新的序列,该序列与旧的序列相同,唯一的区别是在新序列的索引位置有一个新的字符。索引参数必须大于或等于0,并且小于StringBuffer对象所包含的字符串的长度。
语法
public void setCharAt(int index, char ch)
参数: 该方法需要两个参数。
index : 整数类型的值,指的是要设置的字符的索引。ch :字符类型的值,指的是新的字符。返回: 此方法不返回任何东西。
异常: 如果索引为负数或大于length(),该方法会抛出IndexOutOfBoundException。
以下程序演示了StringBuffer类的setCharAt()方法
例1 :
// Java program to demonstrate// the setCharAt() Method. class GFG { public static void main(String[] args) { // create a StringBuffer object // with a String pass as parameter StringBuffer str = new StringBuffer("Geeks For Geeks"); // print string System.out.println("String = " + str.toString()); // set char at index 4 to '0' str.setCharAt(7, '0'); // print string System.out.println("After setCharAt() String = " + str.toString()); }}
输出:
String = Geeks For GeeksAfter setCharAt() String = Geeks F0r Geeks
例2: 演示IndexOutOfBoundsException。
// Java program to demonstrate// Exception thrown by the setCharAt() Method. class GFG { public static void main(String[] args) { // create a StringBuffer object // with a String pass as parameter StringBuffer str = new StringBuffer("Geeks for Geeks"); try { // pass index -1 str.setCharAt(-1, 'T'); } catch (Exception e) { System.out.println("Exception:" + e); } }}
输出:
Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1
参考资料:
https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuffer.html#setCharAt(int, char)
