介紹java操作字串類的主要方法

2021-08-28 06:14:23 字數 1789 閱讀 2597

1、length方法

length()方法的用法如下所示:

public static void main(string args)
輸出結果為:

2、charat方法

charat方法的用法如下所示:

public static void main(string args)
索引值從0開始,返回的是index+1的字元。輸出結果為:

i

d

3、equals方法和equalslgnorecace方法

equals(string s)方法用來比較當前字串物件的實體是否與引數指定的字串s的實體相同。該方法忽略大小。它的用法如下:

public static void main(string args)
輸出結果為:

s1.equals(s2)的值為: true

s1.equals(s3)的值為: false

4、compareto和comparetolgnorecase方法

compareto()按辭典順序與引數s指定的字串比較大小。如果當前字串與s相同,該方法返回值為0;如果當前字串物件大於s,該方法返回正值;如果小於s,該方法返回負值。comareto()用法例項如下所示:

public static void main(string args)
輸出結果為:

6、startswith和endswith方法

startswith(string prefix)和endswith(string suffix)方法用來測試此字串是否以指定的字首開始或結束。相關用法如下

public static void main(string args)
輸出結果為:

tom.startswith("220")的值為: true

jerry.startswith("220")的值為: false

7、regionmatches方法

regionmatches(int firststart,string other,int ortherstart,int length)方法用來從當前字串引數firststart指定的位置開始處取長度 為length的乙個子串,並將這個子串和引數other指定的乙個子串進行比較。其中other指定的子串是指從other字串的ortherstart所指定的位置開始,擷取長度為length的乙個子串。如果兩個子串相同該方法就返回true,否則返回false。該方法的過載方法如下

public boolean regionmatches(boolean b, int firststart,string other,int ortherstart,int length)可以通過引數b決定是否忽略大小寫,當b取true時,忽略大小寫。其相關用法如下所示。

public static void main(string args)
輸出結果為:

true

true

Java 字串常用操作(String類)

string提供了兩種查詢字串的方法,即indexof與lastindexof方法。1 indexof string s 該方法用於返回引數字串s在指定字串中首次出現的索引位置,當呼叫字串的indexof 方法時,會從當前字串的開始位置搜尋s的位置 如果沒有檢索到字串s,該方法返回 1 string...

Java 字串常用操作(String類)

string提供了兩種查詢字串的方法,即indexof與lastindexof方法。1 indexof string s 該方法用於返回引數字串s在指定字串中首次出現的索引位置,當呼叫字串的indexof 方法時,會從當前字串的開始位置搜尋s的位置 如果沒有檢索到字串s,該方法返回 1 1 stri...

Java 字串常用操作(String類)

字串查詢 indexof string s 該方法用於返回引數字串s在指定字串中首次出現的索引位置,當呼叫字串的indexof 方法時,會從當前字串的開始位置搜尋s的位置 如果沒有檢索到字串s,該方法返回 1 string str we are students int size str.index...