String
一、方法
1.拼接
//字符串
String str = "ab12";
String str1 = "cd34";
//拼接字符串
System.out.println("123"+"abc");
System.out.println("123"+str);
//任意类型与字符串拼接,结果为字符串
System.out.println(123+str);
//+加号运算优先级相同
System.out.println(12+23+str);
System.out.println(str+12+23);
结果
123abc
123ab12
123ab12
35ab12
ab121223
2.字符数组
String s1, s2, s3, s4, s5, s6, s7, s8;
s1 = "123";
s2 = "123";
s3 = "1" + "2" + "3";
s4 = new String("123");// 凡是new的对象都是新的对象
s5 = new String("123");
char[] c = {
'1', '2', '3' };
s6 = new String(c);
s7 = "12";
s8 = s7 + new String("3");
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s1 == s4);
System.out.println(s4 == s5);
System.out.println(s5 == s6);
System.out.println(s1 == s8);
结果
true
true
false
false
false
false
3.equals()
比较两个对象的内容是否一致
1.判断两个对线是否是一个对象
2.判断类型是否一致
3.判断值是否一样
String s1 = null;
String s2 = "123";
//使用已知变量调用equals
System.out.println(s1.equals(s2));
System.out.println(s2.equals(s1));
结果
报错
false
4.toCharArray
String s2 = "123";
//将字符串转换为char数组
char[] arr = s2.toCharArray();
System.out.println(Arrays.toString(arr));
结果
[1, 2, 3]
5.indexOf
String = "123";
//下标2在s2中开始出现的位置
int index = s2.indexOf("2");
System.out.println(index);
结果
1
6.lastIndexOf
int index;
String s2 = "123465623565234";
//输出23在字符串中最后出现的位置
index = s2.lastIndexOf("23");
System.out.println(index);
结果
12
7.charAt
//charAt
String s2 = "123465623565234";
//下标3处的数据
char c1 = s2.charAt(3);
System.out.println(c1);
结果
4
8.substring
String s2 = "123465623565234";
String s = s2.substring(4);//从下标为4处截取到最后
System.out.println(s);
s = s2.substring(4, 8);//从下标为4处截取到下标为8(不包括8)
System.out.println(s);
结果
65623565234
6562
9.split
String s2 = "324214351453";
//将s2根据1进行分割成数组
String[] str_arr = s2.split("1");
System.out.println(Arrays.toString(str_arr));
结果
[3242, 435, 453]
10.replace
String s2 = "324214351453";
//将1全部替换为一
String sl = s2.replace("1", "一");
System.out.println(sl);
结果
3242一435一453
二、工具类
StringBuffer和StringBuilder
StringBuffer strB = new StringBuffer();//线程安全,多线程运行慢
strB.append("123");//在原内容上追加新的内容
System.out.println(strB.toString());
StringBuilder strBu = new StringBuilder();//不安全,速度快
strBu.append("helloWorld");
System.out.println(strBu.toString());
结果
123
helloWorld