Java中String類的常用方法簡介

String類的常用方法簡介

  1. char cahrAt(int index)方法,使用charAt方法輸入一個int index值即可返回索引值的字符.
		String s1 = "abcdefgh";
        System.out.println(s1.charAt(3));//輸出:d
  1. int comepareTo(String anotherString)方法,按照字典順序進行比較兩個字符串。比較字符串時,從第一個字母開始比較,若一樣則比較下一個字符。
		String s2 = "abc";
        String s3 = "abf";
        System.out.println(s2.compareTo(s3));//c-f=-3  輸出-3
        String s2 = "abc";
        String s3 = "aff";
        System.out.println(s2.compareTo(s3));//b-f=-4  輸出-4
  1. String concat(String str)方法,將指定字符串連接到此字符串的結尾.
		String s4 = "abc";
        String s5 = "def";
        System.out.println(s4.concat(s5));//輸出:abcdef
  1. boolean contains(CharSequences s)方法,判斷此字符串是否包含指定的字符串,如果是則返回爲true否則返回false。
		String s4 = "abc";
        System.out.println(s4.contains("ab"));//輸出:true
        System.out.println(s4.contains("e"));//輸出:false
  1. boolean startsWith(String str)和boolean endWith(String str)方法,分別是判斷字符串是否是以指定的字符串開始或結尾
		String s4 = "abc";
        System.out.println(s4.startsWith("ab"));//輸出:true
        System.out.println(s4.endsWith("c"));//輸出:true
  1. boolean isEmpty(),判斷此字符串是否爲空
 		String s5 = "";
        System.out.println(s5.isEmpty());//輸出爲:true
  1. byte[] getTypes()使用平臺默認字符集將此String編碼爲byte序列,並將結果存儲在一個新的byte數組中
		String s7 = "abcde";
        byte[] bytes = s7.getBytes();
        for (byte b:
             bytes) {
            System.out.println(b);
        }//輸出97 98 99 100 101 
  1. int hashcode(),返回此字符串的哈希碼
		String s7 = "abcde";
		System.out.println(s7.hashCode());//輸出92599395
  1. int indexOf(int ch),返回指定字符在此字符串中第一次出現處的索引
    int indexOf(String str),返回指定子字符串在此字符串中第一次出現處的索引
		String s7 = "abcde";
		System.out.println(s7.indexOf(99));//輸出2
        System.out.println(s7.indexOf("c"));//輸出2
  1. int indexOf(int ch, int fromIndex),返回在此字符串中第一次出現指定字符處的索引,從指定的索引開始搜索。
    int indexOf(String str,int fromIndex),返回在此字符串中第一次出現指定子字符串的索引,從指定的索引開始搜索。
		String s8 = "abcdeabcde";
		System.out.println(s8.indexOf(100,4));//輸出8
        System.out.println(s8.indexOf("d",4));//輸出8
  1. int lenth(),返回字符串的長度
		String s8 = "abcdeabcde";
		System.out.println(s8.length());//輸出10
  1. String replace(char oldChar,char new Char),返回一個新的字符串,它是通過用 newChar 替換此字符串中出現的所有 oldChar 得到的
 		String s9 = "abc";
        String s10 = "def";
        System.out.println(s9.replace("bc",s10));//輸出adef
  1. char[] toCharArray(),將此字符串轉換爲一個新的字符數組
		String s10 = "def";
 		char[] chars = s10.toCharArray();
        for (char c :
                chars) {
            System.out.println(c);
        }//輸出d e f
  1. String subString(int beginIndex),返回一個新的字符串,是此字符串的一個子字符串,返回的新的字符串包含頭的開始部分
    String subString(int brginIndex,int endIndex),返回一個新的字串,是截取的此字符串的一個子字符串,返回的新的字符串包含頭但是不包含尾
		String s11 = "abcdefgh";
        System.out.println(s11.substring(1));//輸出bcdefgh
        System.out.println(s11.substring(1,3));//輸出bc
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章