天天看點

c++ string類的常用方法_Java中String類的幾種常用方法介紹1. length()2. substring(int beginIndex, int endIndex)3. charAt(int index):char4. indexOf(String str)5. isEmpty()6. replaceAll(String regex, String replacement)

c++ string類的常用方法_Java中String類的幾種常用方法介紹1. length()2. substring(int beginIndex, int endIndex)3. charAt(int index):char4. indexOf(String str)5. isEmpty()6. replaceAll(String regex, String replacement)

1. length()

  • 傳回值:int
  • 說明:傳回指定字元串的長度
public static void main(String[] args) {String str = "This is a computer.";// 傳回指定字元串的長度int length = str.length();System.out.println(length); // 19}
           

2. substring(int beginIndex, int endIndex)

  • 入參:beginIndex是開始索引的位置,endIndex結束索引的位置
  • 傳回值:String
  • 說明:截取字元串,索引是從0開始,截取的字元串隻截取到結束索引之前,以下程式中,beginIndex是2,對應i,endIndex是11,對應o,截取之後不是"is is a co",而是"is is a c",是以,使用這個方法時,要注意endIndex指向的位置
public static void main(String[] args) {String str = "This is a computer.";// 截取字元串String newStr = str.substring(2, 11);System.out.println(newStr); // is is a c }
           

3. charAt(int index):char

  • 入參:int
  • 傳回值:char
  • 功能:指定索引,傳回索引處的字元
public static void main(String[] args) {String str = "This is a dog.";// 傳回指定索引處的charchar ch = str.charAt(3);System.out.println(ch); // s}
           

4. indexOf(String str)

  • 入參:String
  • 傳回值:int
  • 說明:傳回指定字元在該字元串中第一次出現的索引,在"This is a computer."中,有兩個"is",indexOf(String str)方法可以擷取某個字元串第一出現的位置
public static void main(String[] args) {String str = "This is a computer.";// 傳回指定字元在該字元串中第一次出現的索引int index = str.indexOf("is");System.out.println(index); // 2}
           

5. isEmpty()

  • 傳回值:boolean
  • 說明:驗證字元串是否為空,使用這個方法是要注意,被驗證的字元串必須是執行個體化對象,如果字元串是null,會抛出異常java.lang.NullPointerException。另外,多個空格同樣不為空,比如str3就是多個空格組成的字元串,但不為空
public static void main(String[] args) {String str1 = "This is a computer.";String str2 = "";String str3 = " ";// 驗證字元串是否為空boolean result1 = str1.isEmpty();boolean result2 = str2.isEmpty();boolean result3 = str3.isEmpty();System.out.println(result1); // falseSystem.out.println(result2); // trueSystem.out.println(result3); // false}
           

6. replaceAll(String regex, String replacement)

  • 入參:regex指定被替換的字元串,replacement指定替換的字元串
  • 傳回值:String
  • 說明:替換字元串中指定的内容
public static void main(String[] args) {String str = "小明是一個學生";// 替換字元串中指定的内容String newStr = str.replaceAll("學生
           

繼續閱讀