java.lang.String类

String  字符串   是一个常量,它的值在创建之后不能更改,实际上String是一个引用数据类型,会在内存地址值中创建一块区域去存储这个值,但这个值无法去改变,如果改变这个值,只是重新创建了一个内存区域去存储这个值。
public staitc void mian(Sttring[] args){
    String a = "abc";//给a赋值为abc
    a="def";//实际a原来的值并没有变,还是存储在内存里,只是a指向了另一个内存值,这个值为"def"
}

String类中常用的方法
    public static void main(String[] args){
        String a = "hello word";
        //length()
        system.out.println(a.length());//字符串的长度,结果为  10

        //toUpperCase()
        system.out.println(a.toUpperCase());//小写转大写,结果为  HELLO WORD

        //toLowerCase()
        system.out.println(a.toLowerCase());//大写转小写,结果为  hello word

        //charAt()
        system.out.println(a.charAt(7));//返回指定索引处的char值,即从第一个字母起第7个字母是什么  结果为  o
        //indexOf()
        system.out.println(a.indexOf('w'));//返回指定字符在该字符串中第一次出现的索引   结果为   6

        system.out.println(a.indexOf("word"));//返回指定字符串在该字符串中第一个字符的索引  结果为   6

        //equalsIgnoreCase()
        system.out.println(a.equalsIgnoreCase("HELLO WORD"));//忽略大小写比较   结果为   true

        //comepareTo()
        system.out.println(a.comepareTo("girl"));//按字典顺序比较两个字符串的大小,若返回负数,则前小后大,正数则前大后小

        //endsWith()
        system.out.println(a.endsWith("word"));//该字符串是否以指定参数结尾    结果为true

        //stratsWith()
        system.out.println(a.stratsWith("hello"));//该字符串是否以指定参数开头   结果为true

        //subString()
        system.out.println(a.subString(3,6));//截取字符串,前闭后开,取到相对应的索引值,即取hello word 第3个字母到第6个字母之间的值   结果为   "o w"

        //replace()
        system.out.println(a.replace(" ","+"));//替换一个字符串  即把"hello word"里所有的空格换为+号

        //字符串的拆分 split()
       String[] ss = a.split(" ");//以空格为单位拆分字符串a,得到1个字符串数组
       system.out.println(ss[0]+" "+ss[1]);//值为 hello word
}

猜你喜欢

转载自jy00768521.iteye.com/blog/2293507