目录
StringBuffer(线程安全)
- StringBuffer(线程安全)
- 字符串反转
- 字符串的插入
- 字符串的替换
- StringBuilder(非线程安全)
- 线程的同步与异步
- 区别
- 学习心得
为了解决String 内容无法修改的设计性的问题,所以在jdk里面针对字符串又定义了另外一个处理类:java.lang.StringBuffer类,该类是在jdk 1.0的时候提供的,首先来观察一下StringBuffer类的基本的操作方法:
package com.yootk.demo;
public class YootkDemo { // 李兴华编程训练营:yootk.ke.qq.com
public static void main(String[] args) throws Exception {
StringBuffer buffer = new StringBuffer() ; // 实例化了一个StringBuffer类的对象
buffer.append("沐言科技:").append("www.yootk.com").append("\n") ; // 字符串连接
change(buffer); // 引用传递
System.out.println(buffer);
}
public static void change(StringBuffer temp) { // 接收StringBuffer引用
temp.append("李兴华编程训练营:").append("yootk.ke.qq.com") ; // 修改StringBuffer内容
}
}
字符串反转
package com.yootk.demo;
public class YootkDemo { // 李兴华编程训练营:yootk.ke.qq.com
public static void main(String[] args) throws Exception {
StringBuffer buffer = new StringBuffer(30) ; // 可以容纳30个长度的字符串
buffer.append("李兴华编程训练营:").append("yootk.ke.qq.com") ;
System.out.println(buffer.reverse()); // 字符串反转(数组反转)
}
}
package com.yootk.demo;
public class YootkDemo { // 李兴华编程训练营:yootk.ke.qq.com
public static void main(String[] args) throws Exception {
StringBuffer buffer = new StringBuffer(30) ; // 可以容纳30个长度的字符串
buffer.append("yootk.ke.qq.com").insert(0, "李兴华编程训练营:") ;
System.out.println(buffer);
}
}
字符串的替换
package com.yootk.demo;
public class YootkDemo { // 李兴华编程训练营:yootk.ke.qq.com
public static void main(String[] args) throws Exception {
StringBuffer buffer = new StringBuffer(30) ; // 可以容纳30个长度的字符串
buffer.append("yootk.ke.qq.com").insert(0, "李兴华编程训练营:") ;
System.out.println(buffer.replace(9,25, "www.yootk.com"));
System.out.println(buffer.delete(0, 9));
}
}
package com.yootk.demo;
public class YootkDemo { // 李兴华编程训练营:yootk.ke.qq.com
public static void main(String[] args) throws Exception {
StringBuilder buffer = new StringBuilder(30) ; // 可以容纳30个长度的字符串
buffer.append("yootk.ke.qq.com").insert(0, "李兴华编程训练营:") ;
System.out.println(buffer.replace(9,25, "www.yootk.com"));
System.out.println(buffer.delete(0, 9));
}
}
StringBuffer是线程安全的,StringBuilder是非线程安全的。我既然一直都记反了。