学习系统类就是学习系统定义好的方法
equals比较字符串的值
==比较对象的地址
String s1 = "abc";
// new 声明在 堆内存中
String s2 = new String("abc");
String s3 = "abc";
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s1.equals(s2));
输出:false , true , true
equalsIgnoreCase 判断两个字符串是否相等(忽略大小写)
String s1 = "ABC";
boolean b1 = s1.equals("abc");
System.out.println(b1);
输出:true
toLowerCase字符串转小写
String s1 = "ABC";
String s2 = s1.toLowerCase();
System.out.println(s2);
输出:abc
toUpperCase字符串转大写
String s1 = "abc";
String s2 = s1.toUpperCase();
System.out.println(s2);
输出:ABC
contains是否包含这个字符串
String s1 = "abcdef";
boolean b1 = s1.contains("abc");
System.out.println(b1);
输出:true
concat拼接字符串
String s1 = "abc";
String s2 = "def";
String s3 = s1.concat(s2);
System.out.println(s3);
输出:abcdef
startsWith是否以这个前缀开头
String s1 = "www.baidu.com";
boolean b1 = s1.startsWith("www");
System.out.println(b1);
输出:true
endsWith是否以这个后缀结尾
String s1 = "www.baidu.com";
boolean b1 = s1.endsWith("com");
System.out.println(b1);
输出:true
charAt根据索引返回对应字符
String s1 = "abcdef";
char c1 = s1.charAt(5);
System.out.println(c1);
输出:f
indexOf根据字符获取在字符串中的位置
String s1 = "abacadaeaf";
// 从开始找第一个是该字符串的索引
int index1 = s1.indexOf('a');
System.out.println(index1);
// 从传入的索引位置开始寻找(包括当前字符)
int index2 = s1.indexOf('a',5);
System.out.println(index2);
输出:0 , 6
toCharArray把字符串转化为字符数组
String s1 = "abc";
char[] arr = s1.toCharArray();
for(char c :arr) {
System.out.println(c);
输出:
a
b
c
扫描二维码关注公众号,回复:
3420232 查看本文章
isEmpty判断字符串是否为空
// 声明一个空字符串
String s1 = "";
// 指向空的引用
String s2 = null;
boolean b1 = s1.isEmpty();
boolean b2 = s2.isEmpty();
System.out.println(b1);
System.out.println(b2);
输出:
true
报错,不能使用null来调用方法,会出现空指针异常
compareTo字符串比较
String s1 = "abc";
String s2 = "abd";
String s3 = "abcde";
int resault1 = s1.compareTo(s2);
int resault2 = s1.compareTo(s3);
System.out.println(resault1);
System.out.println(resault2);
输出:-1,-2
注释:
- 相等返回 0
- 前面大返回正值,前面小返回负值
- 当字符串长度相等
返回第一个不相等两个字符的ASCII码的差值 - 当字符串长度不相等(未超出部分相等时)
返回两个字符串长度的差值
substring获取子字符串
String s1 = "abcdefg";
String s2 = s1.substring(3);
// 留头不留尾,相对于截取[0,2]
String s3 = s1.substring(0, 3);
System.out.println(s2);
System.out.println(s3);
输出:defg,abc
trim去除首尾的空格
String s1 = " abc def ";
String s2 = s1.trim();
System.out.println(s2);
输出:abc def
replace替换字符
String s1 = "abababab";
String s2 = s1.replace('a', 'b');
System.out.println(s2);
输出:bbbbbbbb
split切割
String s1 = "www.baidu.com";
// 按点切割,使用转义字符 \\
String[] strs = s1.split("\\.");
for(String s :strs) {
System.out.println(s);
}
输出:
www
baidu
com