**StringBuffer:**缓冲区,本身也是操作字符串,但是他可以更改
public static void main(String[] args) {
StringBuffer sb=new StringBuffer();
sb.append("123123");
System.out.println(sb.toString());
tell(sb);
System.out.println(sb.toString());
}
public static void tell(StringBuffer s) {
s.append("abvdabcd");
输出结果:
123123
123123abvdabcd
通过append方法修改StringBuffer字符串,通过toString输出
public static void main(String[] args) {
StringBuffer sb=new StringBuffer();
sb.append("Hello");
sb.insert(0, "i love ");
System.out.println(sb.toString());
sb.replace(1, 3, "123");
System.out.println(sb.toString());
}
输出结果:
i love Hello
i123ove Hello
通过insert方法插入字符串:(起始位,“插入的字符串”)
通过replace方法替换字符串:(起始位,终点位,“替换的字符串”)
案例:
需要输出结果:
abcd0123456789101112……99
方法一:
String a="abcd";
for(int i=0;i<100;i++) {
a=a+i;
}
System.out.println(a);
此方法通过for循环,为每个a重新开辟内存空间,非常消耗内存
方法二:
StringBuffer a=new StringBuffer();
a.append("abcd");
for(int i=0;i<100;i++) {
a.append(i);
}
System.out.println(a.toString());
StringBuilder:作为BUFFER的简易替换,被单线程使用时,建议用这个,若涉及安全,则用buffer
String延展:
String字符串内容不可更改,更改的是其地址(占用内存)
String str="12345";
System.out.println(str.length());
char data[]=str.toCharArray();
for(int i=0;i<data.length;i++) {
System.out.print(data[i]+" ");
}
输出结果:
6
a 1 2 3 4 5 0
charAt()从字符串提取指定位置的字符
System.out.print (str.charAt(5));
getBytes()字符串与byte数组转换
byte bytes[]=str.getBytes();
for(int l=0;l<bytes.length;l++){
System.out.print(new String(bytes)+"\t");
}
输出结果:
a12345 a12345 a12345 a12345 a12345 a12345
检索字符串中存在的字符并定位indexOf()
System.out.println(str.indexOf("a"));
去掉字符串的前后空格trim()
System.out.print(str.trim());
从字符串中提取子字符串subString()
System.out.println(str.substring(0,4));
大小写转换toLowerCase()toUpperCase()
System.out.print(str.toUpperCase());
判断字符串的开头结尾字符endsWith()startWith(),返回值为boolean类型
System.out.print(str.endsWith("1"));
替换字符串中的一个字符replace()
System.out.print(str.replace("1234", "ABCD"));