一、String
1、String类是不可变的字符序列。
例
public class Test8 { public static void main(String[]args){ String s ="hello"; String s1 = "world"; s += s1; //会在内存中新开辟一块区域用来装s和s1的内容,在将s指向该区域,原有的s会被JVM回收 } }二、StringBuffer
1、StringBuffer代表可变的字符序列。
例
public class Test8 { public static void main(String[]args){ StringBuffer a = new StringBuffer("hello"); StringBuffer b = new StringBuffer("world"); a.append(b);//会在a的内存区域后面开辟内存直接添加b的内容 System.out.println(a); } }三、String常用方法
/* public char charAt(int index):返回第index个字符 public int length():返回字符长度 public int indexOf(String str):返回字符串中出现str的第一个位置 public int indexOf(String str,intfromIndex):返回从fromIndex开始出现str的第一个位置 public boolean equalsIgnoreCase(String another):比较字符串与another是否一样(忽略大小写) public String replace(char oldChar,char newChar):在字符串中用newChar字符替换oldChar字符 public boolean startsWith(String prefix):判断字符串是否以prefix字符串开头 public boolean endsWith(String suffix):判断字符串是否以suffix结尾 public String toUpperCase():返回一个字符串为该字符串的大写形式 public String toLowerCase():返回一个字符串为该字符串的小写形式 public String substring(int beginIndex):返回该字符串从beginIndex开始到结尾的字符串 public String substring(int beginIndex,intendIndex):返回该字符串从beginIndex开始到endIndex之间的字符串 public String trim():返回将该字符串去掉开头和结尾空格后的字符串(中间空格不会去掉) public static String valueOf(Objcect obj):把obj转成字符串 public String[] split(String regex):将一个字符串按照指定的分隔符分隔,返回分隔后在字符串数组 */四、StringBuffer例
public class Test8 { public static void main(String[]args){ String s = "Microsoft"; char[] a = {'a','b','c'}; StringBuffer sb1 = new StringBuffer(s); sb1.append("/").append("IBM") .append("/").append("sun"); System.out.println(sb1); StringBuffer sb2 = new StringBuffer("数字"); for(int i=0; i<=9; i++){ sb2.append(i); } System.out.println(sb2); sb2.delete(8,sb2.length()).insert(0,a); System.out.println(sb2); System.out.println(sb2.reverse());//反序sb2 } }