天天看點

Java--幾個常用的String對象的方法

1) length() 方法

length() 傳回字元串的長度,例如:

  1. String str1 = "微學苑";
  2. String str2 = "weixueyuan";
  3. System.out.println("The lenght of str1 is " + str1.length());
  4. System.out.println("The lenght of str2 is " + str2.length());

輸出結果:

The lenght of str1 is 3

The lenght of str2 is 10

可見,無論是字母、數字,還是漢字,每個字元的長度都是1。

2) charAt() 方法

charAt() 方法的作用是按照索引值獲得字元串中的指定字元。Java規定,字元串中第一個字元的索引值是0,第二個字元的索引值是1,依次類推。例如:

  1. String str = "123456789";
  2. System.out.println(str.charAt(0) + "    " + str.charAt(5) + "    " + str.charAt(8));

輸出結果:

1    6    9

3) contains() 方法

contains() 方法用來檢測字元串是否包含某個子串,例如:

  1. String str = "weixueyuan";
  2. System.out.println(str.contains("yuan"));

輸出結果:

true

4) replace() 方法

字元串替換,用來替換字元串中所有指定的子串,例如:

  1. String str1 = "The url of weixueyuan is www.weixueyuan.net!";
  2. String str2 = str1.replace("weixueyuan", "微學苑");
  3. System.out.println(str1);
  4. System.out.println(str2);

輸出結果:

The url of weixueyuan is www.weixueyuan.net!

The url of 微學苑 is www.微學苑.net!

注意:replace() 方法不會改變原來的字元串,而是生成一個新的字元串。

5) split() 方法

以指定字元串作為分隔符,對目前字元串進行分割,分割的結果是一個數組,例如:

  1. import java.util.*;
  2. public class Demo {
  3.     public static void main(String[] args){
  4.         String str = "wei_xue_yuan_is_good";
  5.         String strArr[] = str.split("_");
  6.         System.out.println(Arrays.toString(strArr));
  7.     }
  8. }

運作結果:

[wei, xue, yuan, is, good]

以上僅僅列舉了幾個常用的String對象的方法