/** 作者: ydj
* 文章类别:JDK1.5新特性
* StringBuilder常用类库的特性
* 1.增
* append()
* insert(offset,数据)
* 2.删
* delete()
* 3.改
* replace()
* setcharAt()
* getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
* 4.查
* indexof()
* 总结:1.与String相比长度是可变的
* 2.可以操作多种数据类型
* 3.线程不同步
* 日期:2018-04-19*/
public class StringBuilderDemo {
public static void main(String[] args){
sbAdd();
sbDelete();
sbChange();
sbChar();
}
/**查找有关的操作*/
private static void sbChar() {
char[] chars = {'a','b','c','d','s','d','f'};
StringBuilder sb = new StringBuilder();
sb.append("Hello ").append("World!!");
if (sb.indexOf("Hello")==-1){
sop("没有找到指定内容");
}else {
sop("指定内容已经找到");
}
sop("反转操作:"+sb.reverse());
/**截取原容器中的内容插入字符数组的指定位置开始处*/
sb.getChars(3,6,chars,3);
for (int i = 0; i < chars.length; i++) {
sop(chars[i]);
}
}
/**更新有关的操作*/
private static void sbChange() {
StringBuilder sb = new StringBuilder();
sb.append("Hello ").append("World!!");
sop("截取前:"+sb);
sop("截取后:"+sb.substring(6,11));
sop("获取字串"+sb.charAt(1));
}
/**删除和替换的有关操作*/
private static void sbDelete() {
StringBuilder sb = new StringBuilder();
sb.append("Hello ").append("World!!");
sop("替换前:"+sb);
sb.replace(6,11,"LBXY");
sb.setCharAt(6,'U');
sop("替换后:"+sb);
sb.delete(6,10);//包含前面,不包含后面
sop("删除后:"+sb);
/**清空缓存的好方法*/
sb.delete(0,sb.length());
sop("删除后:"+sb);
}
/**增的有关操作*/
private static void sbAdd() {
char[] chars = {'a','b','c','d','s','d','f'};
StringBuilder sb = new StringBuilder();
sb.append("Hello").append("World");
/**指定位置插入字符串*/
//sb.insert(0,"ok");
/**指定位置插入字符数组,字符数组中偏移量,插入长度*/
sb.insert(0,chars,3,2);//dsHelloWorld
sb.append("\n");
sb.append("数字 = ").append(100).append("\n");
sb.append("字符 = ").append('A').append("\n");
sb.append("布尔 = ").append(true);
sop(sb.toString());
}
private static void sop(Object obj) {
System.out.println(obj);
}
}
StringBuiler的常见操作
最新推荐文章于 2022-07-14 20:33:29 发布