美文网首页
String基础

String基础

作者: allen丿 | 来源:发表于2020-05-16 07:57 被阅读0次

    string是一个final类,不能被继承,不能被修改。

    它内部使用char[]来存储value的,所以也可以用如下方式构造:

    public static void main(String[] args){
        String s = new String(new char[]{'a','b'});
    }
    
    public static void main(String[] args){
        String s1 = "test";
        String s2 = "test";
        System.out.println(s1 == s2); //true
        System.out.println(s1.equals(s2));//true
    }
    

    **==和equals的区别,这里看似两个都为true,实际上是因为字面量都存在常量池,所以s1和s2都指向同一个对象。 **

    public static void main(String[] args){
        String s1 = "test";
        String s2 = new String("test");
        System.out.println(s1 == s2); //false
        System.out.println(s1.equals(s2)); //true
    }
    

    结论:如果要比较两个字符串对象的值,必须要用equals

    此外字符串还提供很多拼接,截取的方法。

    public static void main(String[] args){
        String s = "Hello,World!";
        s.contains("He"); //true
        s.indexOf("ll"); //2
        s.charAt(4); //o
        s.startsWith("He"); //true
        s.endsWith("ss"); //false
        
        //提取字串的例子
        s.substring(6,12); //World!
        s.substring(6); //World!
        
        //去除空格
        " Hello  ".trim(); //"Hello"
        " Hello ".strip(); //"Hello",相比较trim(),它可以去除/u0000的空格符
        " Hello ".strip
        
    }
    

    相关文章

      网友评论

          本文标题:String基础

          本文链接:https://www.haomeiwen.com/subject/ibtlohtx.html