2.2.1String字符串

    技术2022-07-12  72

    字符串比较

    equals():s1.equals(s2);equalsIgnoreCase():忽略大小写比较。

    去首尾空白字符

    trim():" \tHello\r\n ".trim(); // "Hello"

    替换子串

    根据字符或字符串替换: String s = "hello"; s.replace('l', 'w'); // "hewwo",所有字符'l'被替换为'w' s.replace("ll", "~~"); // "he~~o",所有子串"ll"被替换为"~~" 正则表达式替换: String s = "A,,B;C ,D"; s.replaceAll("[\\,\\;\\s]+", ","); // "A,B,C,D"

    分割字符串

    split()方法:

    String s = "A,B,C,D"; String[] ss = s.split("\\,"); // {"A", "B", "C", "D"}返回值是字符串数组

    格式化字符串

    两个方法用来格式化字符串:传入参数替换占位符 formatted()方法(实例方法)和format()(静态方法)

    public class Main { public static void main(String[] args) { String s = "Hi %s, your score is %d!"; System.out.println(s.formatted("Alice", 80)); System.out.println(String.format("Hi %s, your score is %.2f!", "Bob", 59.5)); } }

    输出

    Hi Alice, your score is 80! Hi Bob, your score is 59.50!

    常用的占位符

    %s:显示字符串;%d:显示整数;%x:显示十六进制整数;%f:显示浮点数。(%.2f 表示两位小数)

    类型转换

    将其他类型转换为String类型:String.valueOf(obj); 将String类型转换为int类型: 需要用到int的包装类Integer:int i = Integer.parseInt("123"); 将String类型转换为boolean: 也需要用到包装类Boolean:boolean b = Boolean.parseBoolean("true");

    String和char[]

    实际上String在内部是用char[]表示的,因此两者之间可以相互转换

    char[] cs = "Hello".toCharArray(); // String -> char[] String s = new String(cs); // char[] -> String

    String和char的编码格式

    两者在java中总是以Unicode类型的编码存在,若想转换需要用:

    byte[] b1 = "Hello".getBytes(); // 按系统默认编码转换,不推荐 byte[] b2 = "Hello".getBytes("UTF-8"); // 按UTF-8编码转换 byte[] b2 = "Hello".getBytes("GBK"); // 按GBK编码转换 byte[] b3 = "Hello".getBytes(StandardCharsets.UTF_8); // 按UTF-8编码转换

    或者

    byte[] b = ... String s1 = new String(b, "GBK"); // 按GBK转换 String s2 = new String(b, StandardCharsets.UTF_8); // 按UTF-8转换

    版本更新(了解)

    String在较老版本中内存存储为char[]类型 在新版本中以byte[]类型存储,目的为了节省内存 char类型占两个字节,而byte类型占一个字节,当String需要一个字节空间时,char类型存储造成了空间浪费,因此byte字节节省空间。

    Processed: 0.018, SQL: 9