Java String demos

public class Test{
    public static void main(String[] args) {
        System.out.println("I am testing");
        
        //how to use substring api
        String s = "abcde";
        System.out.println(s.substring(1,2));
        
        //join
        System.out.println(String.join("/", "a", "b", "c"));
        
        
        // how to change a string
        // 共享带来的高效要胜过提取,拼接带来的低效,前者多,后者少
        // 字符串存放在堆中,自动垃圾回收
        String s_changed = s.substring(1,2) + "e";
        System.out.println(s_changed);
        
        // 字符串是否相等
        System.out.println(s_changed.equals("be"));
        // 忽略case
        System.out.println(s_changed.equalsIgnoreCase("BE"));
        // == 用于检测是否指向同一个引用位置
        // 不推荐用 == 比较字符串是否相等,因为不同引用位置也可能有相等的字符串
        // 比如,+ 或者 substring 产生的字符串不是共享的
        
        //长度为0的字符串的检测
        String s_length_0 = "";
        System.out.println(s_length_0.equals(""));
        
        // 检测字符串是否为null
        String s_null = null;
        System.out.println(s_null == null);
        
        // 检测字符串既不是null也不为空串
        // 下面的顺序不能颠倒,在null上调用方法,会产生错误
        if(s_null != null && s_null.length() != 0) {
            System.out.println("valid!");
        }
        
        // 获取某个idx下的字符
        char first = s_changed.charAt(0);
        System.out.println(first);
        
        // 获取字符数组
        char[] strs = s_changed.toCharArray();
        for(char ss: strs) {
            System.out.println(ss);
        }
        
        // 字符串比较
        System.out.println("valid!".compareTo("v"));
        
        // start with and end with
        String hello = "hello";
        System.out.println(hello.startsWith("he"));
        System.out.println(hello.endsWith("loo"));
        
        // first index of and last index of
        System.out.println(hello.indexOf("h"));
        System.out.println(hello.lastIndexOf("l"));
        
        // replace
        System.out.println(hello.replace("l", "M"));
        
        // change case
        System.out.println(hello.toUpperCase());
        
        String s2trim = "  tttmmm    ";
        System.out.println(s2trim.trim());
        
        // 小字符串频繁拼接开销较大,每次拼接都会产生新的字符串,使用StringBuilder避免这个问题
        StringBuilder bd = new StringBuilder();
        bd.append(hello); 
        bd.append('w'); // char can also be added
        // convert bd to string
        String bd_str = bd.toString();
        System.out.println(bd_str);
        // get length
        System.out.println(bd.length());
        // change a char at index
        bd.setCharAt(0, 'P');
        System.out.println(bd);
        // insert a char
        bd.insert(0, 'X');
        System.out.println(bd);
        // delete char at index
        bd.deleteCharAt(2);
        System.out.println(bd);
        // sbd 效率较高,线程不安全
        // sbf 效率较低,线程安全
        
        
    }
}
原文地址:https://www.cnblogs.com/geeklove01/p/10017385.html