Java基础学习笔记--常用API之StringBuffer类
作者:互联网
package com.common.api;
/*
* 基本介绍:
* 1、StringBuffer是字符串缓冲区
*
* StringBuffer特点:
* 1、长度可变化
* 2、可以直接操作多个数据类型
* 3、最终会通过toString方法编程字符串
*
* 功能:CURD(Create Update Read Delete)
* 1)存储
* StringBuffer append();将指定的数据作为参数添加到已有数据的结尾处
* StringBuffer insert(index,数据);;可以将数据插入到指定index位置
* 2)删除
* StringBuffer delete(int start, int end) 删除缓冲区中的数据,包含start,不包含end
* StringBuffer deleteCharAt(int index) 删除指定位置的字符
* 3)获取
* char charAt(int index)
* int indexOf(String str)
* int lastIndexOf(String str)
* int length()
* String substring(int start, int end)
* 4)修改
* StringBuffer replace(int start, int end, String str)
* void setCharAt(int index, char ch)
* 5)反转
* StringBuffer reverse()
* 6) 缓存区指定数据存储到指定字符数组中
* void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
*/
public class StringBufferDemo {
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void method_update()
{
StringBuffer sb=new StringBuffer("abcde");
sb.replace(1,4,"java");
sop(sb.toString());
sb.setCharAt(0, 'A');
sop(sb.toString());
}
public static void method_add()
{
StringBuffer sb=new StringBuffer();
sb.append(23).append(true).append(45);
sop(sb.toString());
sb.insert(2, "kk");
sop(sb.toString());
}
public static void method_del()
{
StringBuffer sb=new StringBuffer("abcde");
sop(sb.toString());
sb.delete(1, 3);
sop(sb.toString());
sb.deleteCharAt(2);
sop(sb.toString());
//清空缓存区
sb.delete(0, sb.length());
sop("清空缓冲区后结果为:"+sb.toString());
}
public static void main(String[] args) {
// TODO Auto-generated method stub
method_add();
method_del();
method_update();
StringBuffer sb=new StringBuffer("abcdefg");
char[] chs=new char[4];
sb.getChars(1, 4, chs, 1);
for(int i=0;i<chs.length;i++)
{
System.out.printf("chs[%d]=%s ",i,chs[i]);
}
}
}
执行结果为:
23true45
23kktrue45
abcde
ade
ad
清空缓冲区后结果为:
ajavae
Ajavae
chs[0]= chs[1]=b chs[2]=c chs[3]=d
标签:Java,int,StringBuffer,void,sop,API,toString,sb 来源: https://blog.csdn.net/redrose2100/article/details/104681076