String类
字符串构造
public static void main(String[] args) {
//1.直接定义一个字符串
String str = "hello";
System.out.println(str);
//2.通过new String对象
String str2 = new String("xawl");
System.out.println(str2);
//3.通过字符数组进行构造
char[] chars = {'a','b','c'};
String str3 = new String(chars);
System.out.println(str3);
}
字符串查找
输入下标,找单个字符,用charAt方法;
*找字符或字符串,需要返回下标*:
如果是从前往后找,用indexOf方法;
如果是从后往前找,用lastIndexOf方法
截取字符串
截取字符串,可以使用subString
替换字符串
(1)替换字符串中的字符 ,用replace
(2)替换字符串中的字符串 ,用replace或replaceAll
(3)替换字符串中的首个字符串,用replaceFirst
字符串拆分
如果要字符串进行拆分,可以用split
但是要注意如果是特殊分隔符,那就需要转义:\\
如果通过多个分隔符对字符串进行分割可以多次for-each循环分割😐
字符串修改
如果是这样的对字符串修改,那就会导致每次修改都会创建新对象,如果这样10W次, 那效率是非常低下的
所以我们应该避免直接对String类型对象进行修改。
如果非要修改那可以使用StringBuffer和StringBuilder进行修改
相互转化
(1)数字和字符串转化用 String.valueof和Integer.parselnt(或Integer.valueof)
(2)大小写转化用toUpperCase和toLowerCase
(3)字符串和数组转化用toCharArray和new String
(4)格式化输出用format
String对象比较
String s1 = new String("hello");
String s2 = new String("hello");
String s3 = new String("world");
直接比较
System.out.println(s1 == s2); // false
System.out.println(s2 == s3); // false
都会是false,因为new String 是在堆上去创建不同的空间,通过s1,s2,s3,分别去指向他们
(1)也就是对于引用类型,==比较的是地址;
而对于基本类型变量,==比较的是存储的值 ;
(2)String类重写了父类Object中equals方法,
Object中equals默认按照==比较,
String重写equals方法后,就会发生动态绑定
(3)String也重写了compareTo ,可以进行大小关系的比较
System.out.println(s1.compareTo(s1));//0
System.out.println(s2.compareTo(s3));//-15
去除字符串左右空格
去掉字符串中的左右空格,保留中间空格,用trim
public static void main(String[] args) {
String str = " asdasdasdas ";
System.out.println(str.trim());//asdasdasdas
}
StringBuilder类
StringBuffer与StringBuilder都继承自AbstractStringBuilder类,AbstractStringBuilder中也是使用字符数组保存字符串,是可变类。
并且都提供了一系列插入、追加、改变字符串里的字符序列的方法,它们的用法基本相同
下面可以看一下二者的用法
添加字符串
添加任意类型数据的字符串形式,并返回当前对象自身
public static void main(String[] args) {
StringBuilder stringBuilder= new StringBuilder();
stringBuilder.append("hello");
stringBuilder.append(" world");
String s = stringBuilder.toString();
System.out.println(s);
}
逆置字符串**
public static void main(String[] args) {
StringBuilder stringBuilder= new StringBuilder();
stringBuilder.append("hello");
stringBuilder.append("world");
stringBuilder.reverse();
System.out.println(stringBuilder);//dlrowolleh
}
StringBuffer类
apppend
public static void main(String[] args) {
StringBuffer stringBuffer= new StringBuffer();
stringBuffer.append("hello");
stringBuffer.append("world");
System.out.println(stringBuffer);//helloworld
}
逆置字符串
public static void main(String[] args) {
StringBuffer stringBuffer= new StringBuffer();
stringBuffer.append("hello");
stringBuffer.append("world");
stringBuffer.reverse();
System.out.println(stringBuffer);//dlrowolleh
}
//删
s.delete(11, 14);
System.out.println(s);//"hello,张三丰赵敏 true10.5"
//改
//使用 周芷若 替换 索引 9-11 的字符 [9,11)
s.replace(9, 11, "周芷若");
System.out.println(s);//"hello,张三丰周芷若 true10.5"
//插
//在索引为 9 的位置插入 “赵敏”,原来索引为 9 的内容自动后移
s.insert(9, "赵敏");
System.out.println(s);//"hello,张三丰赵敏周芷若 true10.5"
//长度
System.out.println(s.length());//22
System.out.println(s)