一文看懂StringBuffer类中的常用方法(含代码)

1、append(xxx):提供了很多的append()方法, 用于进行字符串拼接

StringBuffer str = new StringBuffer("abc");
str.append("def");
System.out.println(str);//abcdef

2、delete(int start,int end):删除指定位置的内容

StringBuffer str = new StringBuffer("abcdef");
str.delete(1,3);
System.out.println(str);//adef

3、replace(int start, int end, String str):把[start,end)位置替换为str

StringBuffer str = new StringBuffer("abcdef");
str.replace(0,2,"B");
System.out.println(str);//Bcdef

4、insert(int offset, xxx):在指定位置插入xxx

StringBuffer str = new StringBuffer("abcdef");
str.insert(3,"A");
System.out.println(str);//abcAdef

**5、reverse() :把当前字符序列逆转 **

StringBuffer str = new StringBuffer("abcdef");
str.reverse();
System.out.println(str);//fedcba

6、public int indexOf(String str):返回字符串所在位置索引

StringBuffer str = new StringBuffer("abcdef");
int num = str.indexOf("bc");
System.out.println(num);//1

7、public String substring(int start,int end):返回一个从start开始到end索引结束的左闭右开[ )区间的字符串

StringBuffer str = new StringBuffer("abcdef");
String s1 = str.substring(2,5);//左闭右开
System.out.println(s1);//cde

8、public int length():返回字符串长度

StringBuffer str = new StringBuffer("abcdef");
int length = str.length();  //因为重写了length()方法,返回是有效长度,不是底层数组长度
System.out.println(length);//6

9、public char charAt(int n ):返回字符串索引为n的字符

StringBuffer str = new StringBuffer("abcdef");
char ch = str.charAt(2);
System.out.println(ch);//c

10、setCharAt(int n ,char ch):设置字符串索引n处的值为ch

StringBuffer str = new StringBuffer("abcdef");
str.setCharAt(1,'B');
System.out.println(str);//aBcdef

posted on 2021-09-19 16:43  Tianhao丶  阅读(288)  评论(0编辑  收藏  举报

导航