目录
本文所有字符串操作均为以下几个字符串:
String str1 = "hello";
String str2 = "world";
String str3 = "aapigww";
String str4 = "";
一、length()
返回值为字符串的长度
System.out.println(str1 + "的长度为:" + str1.length());
输出结果:hello的长度为:5
二、isEmpty()
判断字符串是否为空,返回值为true或false
System.out.println("str1是否为空:" + str1.isEmpty());
System.out.println("str4是否为空:" + str4.isEmpty());
输出结果:str1是否为空:false
str4是否为空:true
三、equals()
判断两个字符串是否相等,返回值为true或false
System.out.println(str1 + "是否和hello相等:" + str1.equals("hello"));
System.out.println(str1 + "是否等于" + str2 + ":" + str1.equals(str2));
输出结果:hello是否和hello相等:true
hello是否等于world:false
四、compareTo()
比较两个字符串,从第一个开始,返回值为int型数据
1.相同则比较下一个
2.不同则返回两个字符的asc码值的差值
3.如果两个字符串不一样长,可以参与比较的字符又完全一样,则返回两个字符串的长度差值
4.返回为正数表示str1>str3, 返回为负数表示str1<str3, 返回为0表示str1==str3;
System.out.println(str1 + "与" + str3 + "首个不同字符的ASC码差值:" + str1.compareTo(str3));
System.out.println(str3 + "与" + str1 + "首个不同字符的ASC码差值:" + str3.compareTo(str1));
输出结果:hello与aapigww首个不同字符的ASC码差值:7
aapigww与hello首个不同字符的ASC码差值:-7
五、startsWith()
从字符串开头开始判断是否含有给定的字符串或字符,可以从指定下标开始判断,返回值为true或false
System.out.println(str1 + "的开头是否是h:" + str1.startsWith("h"));
System.out.println(str1 + "第2个字符往后是否是ll:" + str1.startsWith("ll",1));
输出结果:hello的开头是否是h:true
hello第2个字符往后是否是ll:false
六、endsWith()
从字符串结尾开始判断是否含有给定的字符或字符串,返回值为true或false
System.out.println(str1 + "的结尾是否是lo:" + str1.endsWith("lo"));
输出结果:hello的结尾是否是lo:true
七、IndexOf()
从第一个字符开始查找给定的字符,查找到输出索引,未查找到输出-1
System.out.println("indexOf(): " + str1 + "中l的索引为:" + str1.indexOf("l"));
输出结果:indexOf(): hello中l的索引为:2
八、lastIndexOf()
从最后一个字符倒序查找给定字符,查找到输出索引,未查找到输出-1
System.out.println("lastIndexOf(): " + str1 + "中l的索引为:" + str1.lastIndexOf("l"));
输出结果:lastIndexOf(): hello中l的索引为:3
九、substring()
截取字符串,参数为开始索引和结束索引,截取规则为左闭右开,返回值为截取到的字符串
System.out.println(str3 + "截取pig:" + str3.substring(2,5));
输出结果:aapigww截取pig:pig
十、concat()
和 + 功能一样,可以连接两个字符串,返回值为连接后的新字符串
System.out.println(str1 + "连接" + str2 + ":" + str1.concat(str2));
输出结果:hello连接world:helloworld
十一、replace()
从字符串的首到尾遍历,只要有吻合的字符或字符串,就替换,返回值为替换后的新字符串
System.out.println(str3 + "中的所有a换为A:" + str3.replace("a","A"));
输出结果:aapigww中的所有a换为A:AApigww