字符串比较:
(1)
//字符串比较
String str1 = "hello";
String str2 = "Hello";
//区分大小写比较字符串
System.out.println(str1.equals(str2));
//不区分大小写比较字符串
System.out.println(str1.equalsIgnoreCase(str2));
输出结果为:
false
true
(2)
在String类中compareTo()方法是一个非常重要的方法,该方法返回一个整型,该数据会根据大小关系返回三类内容:
- 相等:返回0.
- 小于:返回内容小于0.
- 大于:返回内容大于0.
//String类中的 compareTo() 比较
System.out.println("A".compareTo("a"));
System.out.println("AB".compareTo("ab"));
System.out.println("ABCD".compareTo("abcd"));
输出结果为:
-32
-32
-32
注意:
(1)compareTo()是一个可以区分大小关系的方法,是String方法里是一个非常重要的方法。
(2)字符串的比较大小规则, 总结成三个字 “字典序” 相当于判定两个字符串在一本词典的前面还是后面. 先比较第一 个字符的大小(根据 unicode 的值来判定), 如果不分胜负, 就依次比较后面的内容
字符串的查找:
(1)contains():判断一个子字符串是否存在
String str = "helloworld";
System.out.println(str.contains("world"));
输出结果为:
true
(2) indexOf():进行位置查找
//只有一个参数的indexOf()查找
String str = "helloworld";
//需要注意,如果内容重复,只能返回查找的第一个位置
System.out.println(str.indexOf("world"));
System.out.println(str.indexOf("hehe"));
//有两个参数的indexOf()查找
String str2 = "helloworld";
System.out.println(str2.indexOf("l"));
//第二个参数表示开始查找的位置
System.out.println(str2.indexOf("l",5));
//lastIndexOf()是从字符串后面开始查找
System.out.println(str2.lastIndexOf("l"));
字符串替换:
String str = "helloworld";
System.out.println(str.replace("l","n"));
System.out.println(str.replaceFirst("l","n"));
输出结果为:
hennoworld
henlowoeld
这里需要我们注意的是:
由于字符串是不可变对象, 我们的替换操作不能修改当前字符串, 而是产生一个新的字符串
字符串的拆分:
可以将一个完整的字符串按照指定的分隔符划分为若干个子字符串
(1)将字符串全部拆分:
//字符串的拆分
String str = "hello world hello you";
String[] array = str.split(" ");
for (String s : array) {
System.out.println(s);
}
输出结果为:
hello
world
hello
you
(2)将字符串部分拆分:
String str = "hello world hello you";
String[] array = str.split(" ",2);
for (String s : array) {
System.out.println(s);
}
输出结果为:
hello
world hello you
注意:
有些特殊字符作为分割符可能无法正确切分, 需要加上转义
例如:拆分IP地址
String str = "192.167.2.1";
String[] array = str.split("\\.");
for (String s : array) {
System.out.println(s);
}
输出结果为:
192
167
2
1
多次拆分:
//多次拆分
String str = "name=zhangsan&age=18";
//第一次拆分
String[] array = str.split("&");
//第二次拆分
for (int i = 0; i < array.length; i++) {
String[] temp = array[i].split("=");
System.out.println(temp[0] + " = " + temp[1]);
}
输出结果为:
name = zhangsan
age = 18
字符串截取:
//字符串的截取
String str = "helloworld";
//(1)从指定的索引截取到结尾
System.out.println(str.substring(5));
//(2)截取部分内容
System.out.println(str.substring(0,5));
输出结果为:
world
hello