您的位置:首页 > 编程语言 > Java开发

JAVA中类String常用方法整理

2018-01-21 13:37 477 查看

Class String

public final class String extends Object

常用的方法小结:
1.public char charAt(int index)
将索引index处的字符返回。例,"hello".charAt(2);则返回'='l'。

2. public boolean equals(Object anObject)
将此字符串与指定对象进行比较。 其结果是true当且仅当该参数不是null并且是String对象,表示相同的字符序列作为该对象。

3. public boolean equalsIgnoreCase(String anotherString)
两个字符串内容对比,忽略大小写,如果相同,则返回true,不同,则返回false。例,boolean b=str1.equalsIgnoreCase(str2);

4. public boolean contentEquals(StringBuffer sb)
String类型的字符串与StringBuffer类型相比,内容相同,返回true,不同,返回false.例,boolean a=str.contenEquals(sb);

5. public boolean startsWith(String str,int index)
某一字符串在索引index处,是否以str开始,如果是,返回true,不是,返回false.例,boolean a=str1.startsWith("bc",0);

6. public boolean endsWith(String str)
某一字符串是否以str结尾,是则返回true,不是,则返回false。

7. public int indexOf(int x/String str)
返回整型x或字符串str在某一字符串中第一次的索引。例,int a =str.indexOf(4); int a=str.indexOf("bc");若没有此值或字符串,返回-1;

8. public int indexOf(int x,int fromIndex)
与上面的方法类似,只是从fromIndex处开始进行搜索。

9.public int indexOf(int x/String str) 和public int indexOf(int x,int fromIndex)与7、8方法相似,只是最后一次出现的索引。

10.public String substring(int beginIndex)
从索引beginIndex处截取字符串,并将此字符串返回。例,“hello".substring(2),返回"llo".

11.public String substring(int beginIndex,int endIndex)
从索引beginIndex到endIndex-1截取字符串,并将此字符串返回。例,“hello".substring(1,2),返回"e".

12.public String concat(String str)
将字符串str追加到字符串的末尾。例,"hello".concat("world"),则返回“helloworld".

13.public String replace(char oldChar,char newChar)
将字符串中的字符oldChar,用newChar替换,并返回新的字符串。例,"happy".replace('p','o'),返回"haooy".

14.public String replaceFirst(String regex,String replacement)
用replacement替换第一次出现的regex。例,"heeheehee".replaceFirst("ee","oo"),返回"hooheehee".

15.public String replaceAll(String regex,String replacement)
用replacement替换全部的regex,与13相似,只是这个替换的是String类型。

16.public String[] split(String regex)
用regex来分隔字符串,并返回一个字符串数组。例,"hello world happy".split(" "),返回{"hello","world","happy"}
注意,若字符串是以|或*等分隔的,则regex须是"\\|"或"\\*"。

17.public String toLowerCase()和public String toUpperCase()
将字符串全部转为小写或大写。例,"hello".toUpperCase(),则返回"HELLO"。

18.public String trim()
将字符串的前导和尾部空格删除,然后返回字符串。例,“ hello ".trim();返回"hello"。

19.public Char[] toCharArray()
将字符串转化为字符数组。

20.public static String valueOf(int i)
将整型数i转化为字符串。例,String s=String.valueOf(89);则s为"89".
还可将其他基本类型应用此方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: