String常用方法简介

1. 创建String对象的常用方法

(1) String s1 = "mpptest"

  (2)  String s2 = new String();

  (3) String s3 = new String("mpptest")

2. String中常用的方法,用法如图所示,具体问度娘

 3.  三个方法的使用: lenth()   substring()   charAt()

package com.mpp.string;

public class StringDemo1 {
    public static void main(String[] args) {
        //定义一个字符串"晚来天欲雪 能饮一杯无"
        String str = "晚来天欲雪 能饮一杯无";
        System.out.println("字符串的长度是:"+str.length());

        //字符串的雪字打印输出  charAt(int index)
        System.out.println(str.charAt(4));

        //取出子串  天欲
        System.out.println(str.substring(2));   //取出从index2开始直到最后的子串,包含2
        System.out.println(str.substring(2,4));  //取出index从2到4的子串,包含2不包含4  顾头不顾尾
    }
}

4. 两个方法的使用,求字符或子串第一次/最后一次在字符串中出现的位置: indexOf()   lastIndexOf()  

   

package com.mpp.string;

public class StringDemo2 {
    public static void main(String[] args) {
        String str = new String("赵客缦胡缨 吴钩胡缨霜雪明");

        //查找胡在字符串中第一次出现的位置
        System.out.println("\"胡\"在字符串中第一次出现的位置:"+str.indexOf("胡"));
        //查找子串"胡缨"在字符串中第一次出现的位置
        System.out.println("\"胡缨\"在字符串中第一次出现的位置"+str.indexOf("胡缨"));

        //查找胡在字符串中最后一次次出现的位置
        System.out.println(str.lastIndexOf("胡"));
        //查找子串"胡缨"在字符串中最后一次出现的位置
        System.out.println(str.lastIndexOf("胡缨"));

        //从indexof为5的位置,找第一次出现的"吴"
        System.out.println(str.indexOf("吴",5));
    }
}

5. 字符串与byte数组间的相互转换

package com.mpp.string;

import java.io.UnsupportedEncodingException;

public class StringDemo3 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        //字符串和byte数组之间的相互转换

        String str = new String("hhhabc银鞍照白马 飒沓如流星");
        //将字符串转换为byte数组,并打印输出
        byte[] arrs = str.getBytes("GBK");
        for(int i=0;i<arrs.length;i++){
            System.out.print(arrs[i]);
        }

        //将byte数组转换成字符串
        System.out.println();
        String str1 = new String(arrs,"GBK");  //保持字符集的一致,否则会出现乱码
        System.out.println(str1);
    }
}

6. 等于运算符和equals之间的区别:

引用指向的内容和引用指向的地址

package com.mpp.string;

public class StringDemo5 {
    public static void main(String[] args) {
        String str1 = "mpp";
        String str2 = "mpp";
        String str3 = new String("mpp");

        System.out.println(str1.equals(str2));  //true  内容相同
        System.out.println(str1.equals(str3));   //true  内容相同
        System.out.println(str1==str2);   //true   地址相同
        System.out.println(str1==str3);   //false  地址不同
    }
}

7. 字符串的不可变性

String的对象一旦被创建,则不能修改,是不可变的

所谓的修改其实是创建了新的对象,所指向的内存空间不变

上图中,s1不再指向imooc所在的内存空间,而是指向了hello,imooc

猜你喜欢

转载自www.cnblogs.com/mpp0905/p/10372061.html
今日推荐