String类
String字符串1、String声明为final,不可被继承2、String实现了Serializable接口:表示字符串是支持序列化的 实现了Comparable接口:表示String可以比较大小3、String内部定义了final char[] value用于存储字符串数据4、String:代表一个不可变的字符序列 体现:当给字符串重新赋值时需要重新指定内存区域地址值 对现有的字符串进行连接操作的时候需要重新指定地址值,不能在原先区域修改赋值 当调用String的replace方法修改指定字符串时,也需要重新指定内存区域5、通过字面量的方式(区别于new)给一个字符串赋值。此时字符串值声明在常量池中6、字符串常量池中是不会存储相同内容的字符串的
拼接:
- 常量与常量的拼接结果在常量池,且常量池中不会存在相同内容的常量
- 只要其中有一个变量,结果就会在堆中
- 如果拼接的结果调用intern()方法,返回字符串常量池地址
常用方法:
- String s1 = “ hello world “;
- String s2 = “hello world”;
- System.out.println(s1.length());
- System.out.println(s1.charAt(9));//返回索引号的字符
- System.out.println(s1.isEmpty());
- System.out.println(s1.toUpperCase());
- System.out.println(s1.toLowerCase());
- System.out.println(s1.trim());//返回字符串的副本,忽略前导空白和尾部空白
- System.out.println(s1.concat(“asd”));//等效于“+”
- System.out.println(s1.compareTo(“ hello world “));//比较字符串大小,负数后者大,关系到字符串排序
- System.out.println(s1.substring(5));//返回从索引处开始截取的新字符串
- String s3 = s1.substring(5, 8);//返回从首尾处截取的字符串
- System.out.println(s1.endsWith(“ “));//字符串是否以这个作为结尾
- System.out.println(s1.startsWith(“he”));//字符串是否以这个作为开始
- System.out.println(s2.startsWith(“l”, 2));//字符串从索引处开始是否是这个
- System.out.println(s2.contains(“lo”));//字符串是否包含这些
- System.out.println(s2.indexOf(“wor”));//字符串中这个的开始的索引,不存在返回-1
- System.out.println(s2.indexOf(“wo”, 8));//从索引处开始找,并且返回索引值,不存在返回-1
- System.out.println(s2.lastIndexOf(“lo”));//从后往前找,返回索引
- System.out.println(s2.lastIndexOf(“lo”,5));//索引处从后往前找,返回索引
- replace(str,str);//字符
- replaceall(regex,str);//把字符串所有部分换成后面的字符(正则)
- String s6 = “1234215353”;
- System.out.println(s6.matches(“123\d{7,8}”));
- split(regex);从正则部分切分
String转换成基本数据类型或者包装类 Integer.parseInt/Double() 基本数据类型或者包装类转换成String String重写的valueOf()还有直接+““
String.toCharArray(); String.getBytes();
StringBuffer和StringBuilder的使用String:不可变的字符序列StringBuffer:可变的字符序列 :线程安全的,效率偏低(建议多线程使用)StringBuilder:可变的字符序列:JDk5.0新增线程不安全,效率高(非多线程使用)
String str = new String(); char[] value = new char[0];String str1 = new String(“abc”); char[] value = new char[]{‘a’,’b’,’c’};
StringBuffer sb1 = new StringBuffer(); char[] value = new char[16];sb1.append(‘a’); value[0] = ‘a’;sb1.append(‘b’); value[1] = ‘b’;
StringBuffer sb2 = new StringBuffer(“abc”); char value = new char[“abc”.length() + 16];
问题1:System.out.printfln(sb2.length()); //打印出来多少 ? 3问题2:扩容问题:如果要添加的数据底层数组放不下了,需要扩容底层数组 默认扩容为原来数组容量的2倍+2,同时将原有数组的元素复制到新数组中。
建议直接创建大容量StringBuffer()
常用方法append()delete()replace()insert()reverse()indexOf()subString()length()charAt()setCharAt()
效率 StringBuilder > StringBuffer > String