笔记摘自 廖雪峰的官方网站-Java教程-Java核心类
字符串和编码
String s1 = "Hello!";
String s2 = new String(new char[] {
'H', 'e', 'l', 'l', 'o', '!'});
Java字符串的一个重要特点就是字符串不可变。这种不可变性是通过内部的private final char[]字段,以及没有任何修改char[]的方法实现的。
字符串比较
比较两个字符串是否相同,必须使用 equals() 方法而不能用 == 。
要忽略大小写比较,使用equalsIgnoreCase()方法。.
public class Main {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "HELLO".toLowerCase();
System.out.println(s1 == s2); //false
System.out.println(s1.equals(s2)); //true
System.out.println(s1.equalsIgnoreCase(s2.toUpperCase())); //true
}
}
String类还提供了多种方法来搜索子串、提取子串。常用的方法有
// 是否包含子串:
"Hello".contains("ll"); // true
//搜索子串的例子:
"Hello".indexOf("l"); // 2
"Hello".lastIndexOf("l"); // 3
"Hello".startsWith("He"); // true
"Hello".endsWith("lo"); // true
//提取子串的例子:
"Hello".substring(2); // "llo"
"Hello".substring(2, 4); "ll"
去除首尾空白字符
使用 trim() 方法可以移除字符串首尾空白字符。空白字符包括空格 \t,\r,\n:
" \tHello\r\n ".trim(); // "Hello"
注意:trim()并没有改变字符串的内容,而是返回了一个新字符串。
另一个strip()方法也可以移除字符串首尾空白字符。它和trim()不同的是,类似中文的空格字符\u3000也会被移除:
"\u3000Hello\u3000".strip(); // "Hello"
" Hello ".stripLeading(); // "Hello "
" Hello ".stripTrailing(); // " Hello"
String还提供了isEmpty()和isBlank()来判断字符串是否为空和空白字符串:
"".isEmpty(); // true,因为字符串长度为0
" ".isEmpty(); // false,因为字符串长度不为0
" \n".isBlank(); // true,因为只包含空白字符
" Hello ".isBlank(); // false,因为包含非空白字符
替换子串
replace()
replaceAll()
分割字符串
split()
拼接字符串
join()
格式化字符串
字符串提供了formatted()方法和format()静态方法,可以传入其他参数,替换占位符,然后生成新的字符串。
public class Main {
public static