常用构造方法
String s1 = new String();
String s2 = new String("hello world");
String s3 = new String(char[] cArr);
//注意一点
String s4 = "abc";
String s5 = new String("abc");
// s4!=s5;原因是String类型是引用类型,引用的是地址;
//new和直接写出来是不一样的;
//s4引用的地址的值是常量,在常量池当中;
//new出来的是在堆中
//两边地址不一样所以是false
常用方法 (jdk1.8 api手册)
String s1 = "hello world";
System.out.println(s1.length());
//11 字符串长度
System.out.println(s1.charAt(0));
//h 索引对应的字符
System.out.println(s1.indexOf("h"));
//0 字符对应的第一次索引的值
System.out.println(s1.indexOf("hello"));
//0 字符串对应的第一次索引的值
System.out.println(s1.contains("world"));
//true 是否包含某个值
System.out.println(s1.equals("hello world"));
//true 判断两个字符串是否相等
System.out.println(s1.replace(" ",","));
//hello,world 替换值(old,new)
System.out.println(Arrays.toString(s1.split(" ")));
//[hello, world] 分割成数组
System.out.println(s1.concat("i'm fine 3q"));
//hello worldi'm fine 3q 拼接字符串
System.out.println(s1.toUpperCase());
//HELLO WORLD 转换成大写
从以上常用方法可以看出来,每一次调用方法,其实s1的值是没有变的 一直在原来的值(hello world)上进行方法调用
因此String类型每次调用方法的时候都要用另一个值进行接收。
String s2 = s1.concat("i'm fine 3q");
//s2 = hello worldi'm fine 3q
//s1 = hello world
StringBuilder和StringBuffer类
StringBuilder和StringBuffer用法一样,不同的是:
StringBuilder类是线程非安全的;
StringBuffer类是线程安全的;
通常用StringBuilder,因为这个类效率高
StringBuilder s1 = new StringBuilder("hello");
s1.append("world");
System.out.println(s1);
//helloworld
s1.reverse();
System.out.println(s1);
//dlrowolleh
StringBuilder类可以直接在原来的地址上改变值,所以可以直接打印出来;
String s = s1.toString();
//可以将StringBuilder类的值转为String类型