常用字符串操作

字符串比较

方法名称描述
public boolean equals(Object anObject区分大小写的比较
public boolean equalsIgnoreCase(String anotherString)不区分大小写的比较
public int compareTo(String anotherString)比较两个字符串的大小关系
String str1 = "hello";
String str2 = "Hello";
System.out.println(str1.equals(str2)); // false
System.out.println(str1.equalsIgnoreCase(str2)); // true


System.out.println("A".compareTo("a")); // -32
System.out.println("a".compareTo("a")); // 0
System.out.println("a".compareTo("A")); // 32
System.out.println("AB".compareTo("AC")); // -1
System.out.println("张".compareTo("三")); // 4375

字符串查找

方法名称描述
public boolean contains(CharSequences)判断一个字符串是否存在
String str = "helloworld";
System.out.println(str.contains("world")); // true

字符串替换

方法名称描述
public String replace(char oldChar, char newChar )替换所有指定的字符
public String replaceAll(String regex, String replacement)替换所有指定的字符串(支持正则表达式)
public String replaceFirst(String regex, String replacement)替换首个内容
String str = "helloworld";
System.out.println(str.replace('o', 'K')); // hellKwKrld
System.out.println(str.replaceAll("o", "K")); // hellKwKrld
System.out.println(str.replaceAll("[a-z]", "6")); // 6666666666
System.out.println(str.replaceFirst("o", "K")); // hellKworld

字符串拆分

方法名称描述
public String[] split(String regex)将字符串全部拆分
public String[] split(String regex, int limit)将字符串部分拆分, 该数组长度就是 limit的极限
String str = "hello china hello world";
String[] ans = str.split(" ");
for (String string : ans) {
	System.out.println(string);
}
// 运行结果
hello
china
hello
world

String str = "hello china hello world";
String[] ans = str.split(" ", 3);
for (String string : ans) {
	System.out.println(string);
}
// 运行结果
hello
china
hello world

字符串截取

方法名称描述
public String substring(int beginIndex)从指定索引截取到结尾
public String substring(int beginIndex, int endIndex)截取部分内容
System.out.println(str.substring(5)); // -world
System.out.println(str.substring(0,5)); // hello

字符串大小写转换

方法名称描述
public String toUpperCase()字符串转大写
public String toLowerCase()字符串转小写
String str = "hello-world";
String str2 = str.toUpperCase();
System.out.println(str2); // HELLO-WORLD
String str3 = str2.toLowerCase();
System.out.println(str3); // hello-world
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值