> 文章列表 > string类有哪些常用方法(string类的方法有哪些)

string类有哪些常用方法(string类的方法有哪些)

string类有哪些常用方法(string类的方法有哪些)

1. lastIndexOf() 方法

lastIndexOf() 方法有以下四种形式:

(1) public int lastIndexOf(int ch): 返回指定字符在此字符串中最后一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。

(2) public int lastIndexOf(int ch, int fromIndex): 返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索,如果此字符串中没有这样的字符,则返回 -1。

(3) public int lastIndexOf(String str): 返回指定子字符串在此字符串中最右边出现处的索引,如果此字符串中没有这样的字符,则返回 -1。

(4) public int lastIndexOf(String str, int fromIndex): 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索,如果此字符串中没有这样的字符,则返回 -1。

string类有哪些常用方法(string类的方法有哪些)

2. replace() 方法

replace() 方法通过用 newChar 字符替换字符串中出现的所有 oldChar 字符,并返回替换后的新字符串。

语法:public String replace(char oldChar, char newChar)

string类有哪些常用方法(string类的方法有哪些)

3. startsWith() 方法

startsWith() 方法用于检测字符串是否以指定的前缀开始。

语法:public boolean startsWith(String prefix, int toffset)

public boolean startsWith(String prefix)

参数

prefix -- 前缀。

toffset -- 字符串中开始查找的位置。

string类有哪些常用方法(string类的方法有哪些)

4. subSequence()方法

subSequence() 方法返回一个新的字符序列,它是此序列的一个子序列。

public CharSequence subSequence(int beginIndex, int endIndex)

参数

beginIndex -- 起始索引(包括)。

endIndex -- 结束索引(不包括)。

string类有哪些常用方法(string类的方法有哪些)

5. substring() 方法

substring() 方法返回字符串的子字符串。(和subSequence方法很像)

public String substring(int beginIndex)

public String substring(int beginIndex, int endIndex)

参数

beginIndex -- 起始索引(包括), 索引从 0 开始。

endIndex -- 结束索引(不包括)。

string类有哪些常用方法(string类的方法有哪些)