String
String对象一旦创建就不能改变 是常量
需要进行大量字符串操作应采用StringBuffer/StringBuilder 最终结果转换成String对象
StringBuffer
线程安全的 可变字符序列
一个类似于String的字符串缓冲区(字符数组)
常用方法
length( ) 返回容器(字符)个数
capacity()容量
append(String str ) 添加字符
insert(int offset, String str)在指定字符插入字符
indexof(String str)在字符数组首次出现 的下标
indexof(String str,int fromIndex)查找字符串首次出现的位置,从某个位置开始
lastindexof(String str)在字符数组最后出现 的下标
reverse( )字符反转
toString()转换为对应的字符串
StringBuilder
线程不安全的 单线程使用 与StringBuffer相比通常优先于StringBuilder,因为它支持所有相同的操作,但因为它不执行同步,所以更快
package com.pojo;
public class StringBuilderDemo {
public static void main(String[] args) {
//StringBuilder sb="abc";//不兼容的类型
//StringBuilder sb=new StringBuilder();//默认16个字符大小的容量
//StringBuilder sb=new StringBuilder();//初始化100容量大小
//StringBuilder sb=new StringBuilder("abc");
StringBuilder sb=new StringBuilder();
sb.append("hello");
sb.append(1.5);
sb.append(true);
System.out.println(sb.length());
System.out.println(sb.capacity());//容量大小
System.out.println(sb.insert(5, "word"));
System.out.println(sb.reverse());//反转
System.out.println(sb.replace(5, 7, "111"));
System.out.println(sb.substring(1, 2));//截取字符串
System.out.println(sb.indexOf("rt"));
}
}
案例
package com.pojo;
import java.util.Arrays;
public class MyStringBuilder {
public static void main(String[] args) {
MyStringBuilderDemo m=new MyStringBuilderDemo();
m.append("hello");
m.append(",java");
m.append("123456");
System.out.println(m.length()+""+m.capacity()+""+m.toString());
}
}
class MyStringBuilderDemo{
private char[] value;//字符数组
private int count=0;//字符数组中存放字符的个数
public MyStringBuilderDemo() {
value=new char[16];
}
public MyStringBuilderDemo(int capacity) {
value=new char[capacity];
}
public MyStringBuilderDemo(String str) {
value=new char[str.length()+16];
}
//得到字符数组中的字符个数
public int length() {
return count;
}
//返回容器的容器大小
public int capacity() {
return value.length;
}
//实现字符串的添加
public MyStringBuilderDemo append(String str) {
int len=str.length();//获取要添加字符串的长度
//确保字符数组能放进去所添加的字符串
ensureCapacity(count+len);
//把要添加的字符串追加到新的指定数组的指定位置后面
str.getChars(0, len,value ,count);
count+=len;//元素个数增加了
return this;
}
private void ensureCapacity(int Capacity) {
//数据超出容量大小 扩容
if (Capacity-value.length>0) {
int newCapacity=value.length*2+2;//扩容后新字符数组的大小
value=Arrays.copyOf(value, newCapacity);
}
}
//把字符数组转换成字符串显示
public String toString() {
return new String(value, 0, count);
}
}