String类的常用方法应用实例
1. equals:比较字符串内容,区分大小写
2. equalsIgnoreCase :忽略大小写,判断内容是否相等
public class StringMethod {
public static void main(String[] args) {
String name1 = "hello";
String name2 = "Hello";
// equals
System.out.println(name1.equals(name2)); // false
// equalsIgnoreCase
System.out.println(name1.equalsIgnoreCase(name2)); // true
}
}
3.length : 获取字符串的长度,字符的个数。
4.indexOf : 获取字符在字符串对象中第一次出现的索引,索引从 0 开始,如果找不到, 返回-1。
5.lastIndexOf : 获取字符在字符串对象中最后一次出现的索引,索引从 0 开始,如果找不到, 返回-1。
public class StringMethod {
public static void main(String[] args) {
String str = "abc@abc@";
int index1 = str.indexOf('@');
int index2 = str.indexOf('d');
int index3 = str.lastIndexOf('@');
System.out.println(str.length()); //8
System.out.println(index1); //3
System.out.println(index2); //-1
System.out.println(index3); //7
System.out.println(str.indexOf("abc")); //0
}
}
6.substring : 截取指定范围的字符串.(截取到索引减一)
public class StringMethod {
public static void main(String[] args) {
String str1 = "hello,张三";
System.out.println(str1.substring(6)); //截取后面的字符 -> 张三
System.out.println(str1.substring(0,5));// 索引从 0 - 5 截取 -> hello
System.out.println(str1.substring(2,5));// -> oll
}
}
7.toUpperCase : 转大写
8.toLowerCase : 转小写
9.concat :连接字符串
10.replace : 替换字符串的字符
11.split : 分割字符串,对于某些分割字符,我们需要转义 比如 | \\ 等
12.compareTo : 比较两个字符串的大小
13.toCharArray : 转换为字符数组
14.format : 格式化字符串,%s 字符串,%c 字符,%d 整型,%.2f 浮点型(四舍五入)
15.charAt : 获取索引处的字符
String s = "jack";
System.out.println(s.charAt(2)); // c
注意: 不能使用 s[2]来获取字符 ,s 是一个对象,不是数组