String
在Java中,String是一个引用类型,它本身也是一个class,实际上字符串在String内部是通过一个char[]数组表示的,String太常用了.
常用:
String str="hello world";
字符串的比较:equal实现 不能使用==来实现
String str1="hello0";
String str2="hello1";
System.out.println(str1.equals(str2));//比较返回
System.out.println(str1.equalsIgnoreCase(str2));//忽略大小写比较
输出:
false
false
查找:
String str="abcdefghijkl";
System.out.println(str.indexOf("b")); //查找下标
System.out.println(str.lastIndexOf("b")); //
System.out.println(str.startsWith("bc")); //起始
System.out.println(str.endsWith("kl")); //末尾
去除首位空白字符
.trim() 去除首位空白字符 它并没有改变字符串的内容,而是返回一个新字符串
.strip() 方法也可以移除字符串首尾空白字符。它和trim()不同的是,类似中文的空格字符\u3000也会被移除
.isEmpty() 判断是否为空
.isBlank() 判断是否包含空白字符
" \tHello\r\n ".trim(); // "Hello"
"\u3000Hello\u3000".strip(); // "Hello"
"".isEmpty(); // true,因为字符串长度为0
" ".isEmpty(); // false,因为字符串长度不为0
" \n".isBlank(); // true,因为只包含空白字符
" Hello ".isBlank(); // false,因为包含非空白字符
替换子串
要在字符串中替换子串,有两种方法。一种是根据字符或字符串替换:
String s = "hello";
s.replace('l', 'w'); // "hewwo",所有字符'l'被替换为'w'
s.replace("ll", "~~"); // "he~~o",所有子串"ll"被替换为"~~"
字符编码
在Java中,char类型实际上就是两个字节的Unicode编码。如果我们要手动把字符串转换成其他编码,可以这样做:
byte[] b1 = "Hello".getBytes(); // 按ISO8859-1编码转换,不推荐
byte[] b2 = "Hello".getBytes("UTF-8"); // 按UTF-8编码转换
byte[] b2 = "Hello".getBytes("GBK"); // 按GBK编码转换
byte[] b3 = "Hello".getBytes(StandardCharsets.UTF_8); // 按UTF-8编码转换
注意:转换编码后,就不再是char类型,而是byte类型表示的数组。
如果要把已知编码的byte[]转换为String,可以这样做:
byte[] b = ...
String s1 = new String(b, "GBK"); // 按GBK转换
String s2 = new String(b, StandardCharsets.UTF_8); // 按UTF-8转换
小结
Java字符串String是不可变对象;
字符串操作不改变原字符串内容,而是返回新字符串;
常用的字符串操作:提取子串、查找、替换、大小写转换等;
Java使用Unicode编码表示String和char;
转换编码就是将String和byte[]转换,需要指定编码;
转换为byte[]时,始终优先考虑UTF-8编码。