StringBuffer类的setCharAt()方法将位置索引处的字符设置为character,这是作为参数传递给方法的值。此方法返回一个新序列,该序列与旧序列相同,只是区别在于新字符ch在新序列的位置索引处存在。 index参数必须大于或等于0,并且小于StringBuffer对象包含的String的长度。
用法:
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 Geeks
After 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