java setcharat_Java StringBuffer setCharAt()用法及代码示例

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值