java可变字符串替换字符,我们如何替换Java中String和StringBuffer的特定部分?

java.lang包的String类表示一组字符。Java程序中的所有字符串文字(例如“ abc”)都实现为此类的实例。

例public class StringExample {

public static void main(String[] args) {

String str = new String("Hello how are you");

System.out.println("Contents of the String: "+str);

}

}

输出结果Hello how are you

字符串对象是不可变的,一旦创建了字符串对象,便无法更改其值,如果尝试这样做,则不能更改其值,而是创建具有所需值的新对象,并且引用移至新创建的对象,而保留前一个对象没用过。

如果需要对String进行大量修改,则使用StringBuffer(和StringBuilder)类。

与Strings不同,StringBuffer类型的对象可以一遍又一遍地修改,而不会留下很多新的未使用对象。它是线程安全的可变字符序列。

例public class StringBufferExample {

public static void main(String[] args) {

StringBuffer buffer = new StringBuffer();

buffer.append("Hello ");

buffer.append("how ");

buffer.append("are ");

buffer.append("you");

System.out.println("Contents of the string buffer: "+buffer);

}

}

输出结果Contents of the string buffer: Hello how are you

替换字符串的特定部分

String类的replace()方法接受两个String值-一个表示要替换的String(子字符串)部分。

另一个代表需要替换指定子字符串的字符串。

使用此方法,您可以替换Java中Sting的一部分。

例public class StringReplace {

public static void main(String[] args) {

String str = new String("Hello how are you, welcome to TutorialsPoint");

System.out.println("Contents of the String: "+str);

str = str.replace("welcome to TutorialsPoint", "where do you live");

System.out.println("Contents of the String after replacement: "+str);

}

}

输出结果Contents of the String: Hello how are you, welcome to TutorialsPoint

Contents of the String after replacement: Hello how are you, where do you live

替换StringBuffer的特定部分

类似地,StringBuffer类的replace()方法接受-两个整数值,表示要替换的子字符串的开始和结束位置。

一个String值,应替换上面指定的子字符串。

使用此方法,可以用所需的String替换StringBuffer的子字符串。

例public class StringBufferReplace {

public static void main(String[] args) {

StringBuffer buffer = new StringBuffer();

buffer.append("Hello ");

buffer.append("how ");

buffer.append("are ");

buffer.append("you ");

buffer.append("welcome to TutorialsPoint");

System.out.println("Contents of the string buffer: "+buffer);

buffer.replace(18, buffer.length(), "where do you live");

System.out.println("Contents of the string buffer after replacement: "+buffer);

}

}

输出结果Contents of the string buffer: Hello how are you welcome to TutorialsPoint

Contents of the string buffer after replacement: Hello how are you where do you live

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值