Java-String類的常用方法

  1. 提取子串

    //s.substring(begin, end);
    //截取 從begin -- end-1 區間內的字符
    String s1 = new String("0123456789");
    String s2 = s1.substring(2, 7);
    System.out.println(s2);

  2. 字符串比較

    String str1 = new String("abc");
    String str2 = new String("ABC");
    int a = str1.compareTo(str2);// a > 0
    int b = str1.compareToIgnoreCase(str2);// b = 0
    boolean c = str1.equals(str2);// c = false
    boolean d = str1.equalsIgnoreCase(str2);// d = true

         

  3. 字符串查找

    //s.idexOf(char a/String str) 用於查找當前字符串中字符或子串,返回字符或子串在當前字符串中從左邊起首次出現的位置,若沒有出現則返回-1。//s.idexOf(char a/String str, int pos) 從pos 位置往右查找 字符a
    //s.lastIndexOf(char a/String str) 從右往左查找
    //s.lastIndexOf(char a/String str, int pos) 從pos 位置看i是往左查找
    String str = "I am a good student";
    int a = str.indexOf('a');//a = 2
    int b = str.indexOf("good");//b = 7
    int b1 = str.indexOf("goood");//b1 = -1
    int c = str.indexOf("g",2);//c = 7
    int d = str.lastIndexOf("a");//d = 5
    int e = str.lastIndexOf("am",5);//e = 2

     

  4. 字符串中字符的大小寫轉換

    String s = new String("Hello World");
    String s1 = s.toLowerCase();//hello world
    String s2 = s.toUpperCase();//HELLO WORLD

     

  5. 字符串中字符的替換

    String str = "asdzxcasd";
    String str1 = str.replace('a','g');//str1 = "gsdzxcgsd"
    String str2 = str.replace("asd","fgh");//str2 = "fghzxcfgh"
    String str3 = str.replaceFirst("asd","fgh");//str3 = "fghzxcasd"
    String str4 = str.replaceAll("asd","fgh");//str4 = "fghzxcfgh"
        

     

  6. 判斷是否存在某個子串

    String str = "123123123123123";
    String s = "12";
    boolean flag = str.contains(s);// flag = true

     

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章