1、append:拼接字符串
public class UsingStringBuffer {
public static void main(String[] args) {
UsingStringBuffer us = new UsingStringBuffer();
us.testFindStr();
}
public static void testFindStr() {
StringBuffer sb = new StringBuffer();
// 拼接字符串 append()方法
sb.append("This is a StringBuffer");
sb.append("wuxp");
System.out.println(sb);
}
}
This is a wdxp
[Finished in 0.9s]
2、indexOf:返回字符串在字符串中最先出现的位置
public class UsingStringBuffer {
public static void main(String[] args) {
UsingStringBuffer us = new UsingStringBuffer();
us.testFindStr();
}
public static void testFindStr() {
StringBuffer sb = new StringBuffer();
sb.append("This is a StringBuffer");
System.out.println("sb.indexOf(\"is\")=" + sb.indexOf("is"));
// 给indexOf方法设置参数,指定匹配的起始位置
System.out.println("sb.indexOf(\"is\")=" + sb.indexOf("is", 3));
// 返回子字符串在字符串中最后出现的位置,如果不存在,返回负数
System.out.println("sb.lastIndexOf(\"is\") = " + sb.lastIndexOf("is"));
// 给lastIndexOf方法设置参数,指定匹配的结束位置 ,从指定位置开始,从后往前
System.out.println("sb.lastIndexOf(\"is\", 1) = " + sb.lastIndexOf("is", 1));
}
}
sb.indexOf("is")=2
sb.indexOf("is")=5
sb.lastIndexOf("is") = 5
sb.lastIndexOf("is", 1) = -1
[Finished in 0.9s]
3、substring:截取字符串
public class UsingStringBuffer {
public static void main(String[] args) {
UsingStringBuffer us = new UsingStringBuffer();
us.testSubStr();
}
public static void testSubStr() {
StringBuffer sb = new StringBuffer();
sb.append("This is abStringBuffer");
// 从(包含)第n位截取到末尾
System.out.println("sb.substring(4)=" + sb.substring(4));
// substring方法截取字符串,可以指定截取的起始位置和终止位置
System.out.println("sb.substring(4,9)=" + sb.substring(4, 9));
}
}
sb.substring(4)= is abStringBuffer
sb.substring(4,9)= is a
[Finished in 0.9s]
待续