java String类常用方法总结
注意:字符串中第一个字符索引是0,最后一个是length()-1。
1.返回给定位置的代码单元,求字符串某一位置字符。
public char charAt(int index)
String str = new String("Hello world!");
char ch = str.charAt(4);//ch='o'
2.返回字符串长度。
public int length()
String str = new String("Hello world!");
int strlength = str.length();//strlength = 12
3.字符串比较
1)public boolean equals(Object anotherObject)//比较当前字符串和参数字符串,在两个字符串相等的时候返回true,否则返回false。
2)public boolean equalsIgnoreCase(String anotherString)//与equals方法相似,但忽略大小写.
String str1 = new String("Hello");
String str2 = new String("HELLO");
boolean a = str1.equals(str2);//a=false
boolean b = str1.equalsIgnoreCase(str2);//b=true
4.提取子串
1)public String substring(int beginIndex)//返回新字符串,该字符串包含原字符串中从beginIndex位置到串尾。
2)public String substring(int beginIndex, int endIndex)//该方法从beginIndex位置起,从当前字符串中取出到endIndex-1位置的字符作为一个新的字符串返回。截取区间为前闭后开。
String str1 = new String("abcdefghi");
String str2 = str1.substring(5);//str2 = "fghi"
String str3 = str1.substring(2,5);//str3 = "cde"
5.大小写转换
1)public String toLowerCase()//所有字符转换成小写
2)public String toUpperCase()//所有字符转换成大写
1 String str = new String("abcDEF");
2 String str1 = str.toLowerCase();//str1 = "abcdef"
3 String str2 = str.toUpperCase();//str2 = "ABCDEF"
6.字符串字符的替换
public String replace(charSequence oldString, charSequence newString)//用字符newString替换当前字符串中所有的oldstring字符,并返回一个新的字符串。charSequence可以为char,也可以为string。
String str = "Hello";
String str1 = str.replace('o','L');//str1 = "hellL"
String str2 = str.replace("llo","lp");//str2 = "Help"
7.查找
1)public int indexOf(int ch/String str)//用于查找当前字符串中字符(代码点)或子串,返回字符或子串在当前字符串中从左边起首次出现的位置,若没有出现则返回-1。
2)public int indexOf(int ch/String str, int fromIndex)//从fromIndex位置向后查找字符(代码点)或子串在当前字符串中从左边起首次出现的位置,若没有出现则返回-1。
3)public int lastIndexOf(int ch/String str)//从字符串的末尾位置向前查找。
4)public int lastIndexOf(int ch/String str, int fromIndex)//从fromIndex位置向前查找。
String str = "Hello world!";
int a = str.indexOf('l');//a = 2
int b = str.indexOf("llo");//b = 2
int c = str.indexOf("w",2);//c = 6
int d = str.lastIndexOf("o");//d = 7
int e = str.lastIndexOf("d",3);//e = -1
8.截去字符串两端的空格
String trim();
String str = " a sd ";
String str1 = str.trim();
int a = str.length();//a = 6
int b = str1.length();//b =
9.判断字符串是否以suffix串开头或结尾
1)boolean statWith(String suffix)判断字符串是否以suffix串开头
2)boolean endWith(String suffix)判断字符串是否以suffix串结尾
1 String str = "asdfgh";
2 boolean a = str.statWith("as");//a = true
3 boolean b = str.endWith("gh");//b = true
10.将str作为分隔符进行字符串分解
String[] split(String str)
String str = "asd!qwe|zxc#";
String[] str1 = str.split("!|#");//str1[0] = "asd";str1[1] = "qwe";str1[2] = "zxc";
还没有评论,来说两句吧...