一、获取字符串的长度:.length()
示例:
//获取字符串的长度
String str = "Hello World!";
int strLength = str.length();
System.out.println(strLength);//输出:12
二、字符串的拼接:.concat()
1.用+进行拼接
2.使用.concat()方法进行拼接
示例:
//拼接字符串
String str1 = "Hello";
String str2 = "World!";
//用+进行拼接
String str3 = str1+str2 ;
//使用.concat()进行拼接
String str4 = str1.concat(str2);
System.out.println(str3); //输出:HelloWorld!
System.out.println(str4); //输出:HelloWorld!
三、字符串的比较:.equals()
1.比较两个字符串是否相等
2.比较两个字符串忽略大小写是否相等
//比较两个字符串是否相等
String str1 = "Hello";
String str2 = "World!";
boolean isOk = str1.equals(str2);
System.out.println(isOk); //输出:false
//比较两个字符串忽略大小写是否相等
String str3 = "HellO";
String str4 = "hElLo";
boolean isOk1 = str3.equalsIgnoreCase(str4);
System.out.println(isOk1); //输出:true
四、字符串的查找:.index()
查找字符或字串在字符串中第一次出现的位置。
示例:
//查找字符或字串在字符串中第一次出现的位置。
String str1 = "Hello World!";
int index = str1.indexOf("o");
System.out.println(index); //输出:4
五、字符串的截取:.substring()
1.从指定位置开始截取
2.从指定范围开始截取
示例:
//1.从指定位置开始截取
String str1 = "Hello World!";
String str2 = str1.substring(2);
System.out.println(str2); //输出:llo World!
//2.从指定范围开始截取
String str3 = "Hello World!";
String str4 = str3.substring(2, 9);
System.out.println(str4); //输出:llo Wor
六、字符串的替换:.replace()
替换字符串中的字符
示例:
//替换字符串中的字符
String str1 = "Hello World!";
String str2 = str1.replace("l", "L");
System.out.println(str2); //输出:HeLLo WorLd
七、字符串的分割:.split()
示例:用指定字符进行分割。
//字符串的分割
String str1 = "Hello World!";
String[] str2 = str1.split("o");
System.out.println(Arrays.toString(str2));
八、字符串的转换:.toUpperCase()、toLowerCase()
1.将小写字母转换成大写
2.将大写字母转换成小写
示例:
//1.将小写字母转换成大写
String str1 = "Hello World!";
String str2 = str1.toUpperCase();
System.out.println(str2); //输出:HELLO WORLD!
//2.将大写字母转换成小写
String str3 = "Hello World!";
String str4 = str3.toLowerCase();
System.out.println(str4); //输出:hello world!
九:字符串去除空格:.trim()
去除字符串前后的空格
示例:
//去除字符串前后的空格
String str1 = " Hello World ! ";
String str2 = str1.trim();
System.out.println(str2); //输出:Hello World !
十、字符串的判空:.isEmpty()
判断字符串是否为空
示例:
//判断字符串是否为空
String str1 = "Hello World!";
boolean isEmpty = str1.isEmpty();
System.out.println(isEmpty); //输出:false
十一、字符串转换为整形:Integer.parseInt(String str)
示例:
//字符串转换为整形:Integer.parseInt(String str)
String str1 = "123456";
int n1 = Integer.parseInt(str1);
System.out.println(n1); //输出:123456