String在Java中是一个比较特殊而且十分常用的类
String类中提供了相当一部分我们需要掌握和理解的方法
现将这些方法大概分个类
一、字符串比较
关于字符串比较的这三个方法都还是比较常用的
equals方法的话基本都比较了解,重写了Object的equals,进行的是字符串内容的比较
与之对应的还有不区分大小写的比较,当我们业务逻辑如此的时候,不要忘记这个方法
CompareTo需要注意他的返回内容
1. 相等:返回0 2. 小于:返回内容小于0 3. 大于:返回内容大于0。
System.out.println("A".compareTo("a")); // -32
System.out.println("a".compareTo("A")); // 32
System.out.println("A".compareTo("A")); // 0
System.out.println("AB".compareTo("AC")); // -1
System.out.println("刘".compareTo("胡"));
JAVA默认unicode,所以哪怕是中文也可以比较出大小,感兴趣的可以比一比你和你的好兄弟好姐妹谁的姓比较大。
二、字符串查找
这里最常用的就是contains和indexof
indexOf()需要注意的是,如果内容重复,它只能返回查找的第一个位置
三、字符串替换
String str = "helloworld" ;
System.out.println(str.replaceAll("l", "_")); //he__oworld
System.out.println(str.replaceFirst("l", "_")); //he_loworld
四、字符串拆分
String str = "hello world hello bro" ;
String[] result = str.split(" ") ; // 按照空格拆分
for(String s: result) {
System.out.println(s);
}
String str = "hello world hello bro";
String[] result = str.split(" ", 2);
for (String s : result) {
System.out.println(s);
}
// hello world hello bro
五、字符串截取
六、其他操作