StringBuffer
public class StringBuffer {
public static void main(String[] args) {
java.lang.StringBuffer sb = new java.lang.StringBuffer();
//增,追加
sb.append("www..com");
System.out.println(sb);
//插入到第几位
sb.insert(4, "weijun魏901");
System.out.println(sb);
//删,删除从下标a到第下标b
sb.delete(10, 11);
System.out.println(sb);
//改,替换
sb.replace(7,8,"J");
System.out.println(sb);
//返回当前容量
System.out.println(sb.capacity());
//返回此序列中指定索引处的 char 值。
System.out.println(sb.charAt(7));
//返回第一次出现的指定子字符串在该字符串中的索引。
System.out.println(sb.indexOf("J"));
//返回最右边出现的指定子字符串在此字符串中的索引。
System.out.println(sb.lastIndexOf("w"));
//返回 String 对象中子字符串最后出现的位置。
System.out.println(sb.lastIndexOf("Jun"));
//返回长度(字符数)。
System.out.println(sb.length());
//将给定索引处的字符设置为 ch。
sb.setCharAt(7,'j');
System.out.println(sb);
//设置字符序列的长度。
sb.setLength(16);
System.out.println(sb);
sb.append("m");
System.out.println(sb);
//返回一个新的字符序列,该字符序列是此序列的子序列。
System.out.println(sb.subSequence(4,13));
System.out.println(sb);
//返回一个新的 String,它包含此字符序列当前所包含的字符子序列。
System.out.println(sb.substring(4));
System.out.println(sb);
//返回一个新的 String,它包含此序列当前所包含的字符子序列。
System.out.println(sb.substring(4,13));
System.out.println(sb);
}
}
StringBuilder
public class StringBuilder {
public static void main(String[] args) {
java.lang.StringBuilder sb = new java.lang.StringBuilder();
//增,追加
sb.append("www..com");
System.out.println(sb);
//插入到第几位
sb.insert(4, "weijun魏901");
System.out.println(sb);
//删,删除从下标a到第下标b
sb.delete(10, 11);
System.out.println(sb);
//改,替换
sb.replace(7,8,"J");
System.out.println(sb);
//返回当前容量
System.out.println(sb.capacity());
//返回此序列中指定索引处的 char 值。
System.out.println(sb.charAt(7));
//返回第一次出现的指定子字符串在该字符串中的索引。
System.out.println(sb.indexOf("J"));
//返回最右边出现的指定子字符串在此字符串中的索引。
System.out.println(sb.lastIndexOf("w"));
//返回 String 对象中子字符串最后出现的位置。
System.out.println(sb.lastIndexOf("Jun"));
//返回长度(字符数)。
System.out.println(sb.length());
//将给定索引处的字符设置为 ch。
sb.setCharAt(7,'j');
System.out.println(sb);
//设置字符序列的长度。
sb.setLength(16);
System.out.println(sb);
sb.append("m");
System.out.println(sb);
//返回一个新的字符序列,该字符序列是此序列的子序列。
System.out.println(sb.subSequence(4,13));
System.out.println(sb);
//返回一个新的 String,它包含此字符序列当前所包含的字符子序列。
System.out.println(sb.substring(4));
System.out.println(sb);
//返回一个新的 String,它包含此序列当前所包含的字符子序列。
System.out.println(sb.substring(4,13));
System.out.println(sb);
}
}
执行结果,都是一样的
可见这两个类的方法可以通用
www..com
www.weijun魏901.com
www.weijun901.com
www.weiJun901.com
34
J
7
4
7
17
www.weijun901.com
www.weijun901.co
www.weijun901.com
weijun901
www.weijun901.com
weijun901.com
www.weijun901.com
weijun901
www.weijun901.com