java String类常用方法总结

末蓝、 2022-03-19 15:15 388阅读 0赞

注意:字符串中第一个字符索引是0,最后一个是length()-1。

1.返回给定位置的代码单元,求字符串某一位置字符。

public char charAt(int index)

  1. String str = new String("Hello world!");
  2. char ch = str.charAt(4);//ch='o'

2.返回字符串长度。

public int length()

  1. String str = new String("Hello world!");
  2. int strlength = str.length();//strlength = 12

3.字符串比较

1)public boolean equals(Object anotherObject)//比较当前字符串和参数字符串,在两个字符串相等的时候返回true,否则返回false。
2)public boolean equalsIgnoreCase(String anotherString)//与equals方法相似,但忽略大小写.

  1. String str1 = new String("Hello");
  2. String str2 = new String("HELLO");
  3. boolean a = str1.equals(str2);//a=false
  4. 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位置的字符作为一个新的字符串返回。截取区间为前闭后开。

  1. String str1 = new String("abcdefghi");
  2. String str2 = str1.substring(5);//str2 = "fghi"
  3. String str3 = str1.substring(2,5);//str3 = "cde"

5.大小写转换

1)public String toLowerCase()//所有字符转换成小写
2)public String toUpperCase()//所有字符转换成大写

  1. 1 String str = new String("abcDEF");
  2. 2 String str1 = str.toLowerCase();//str1 = "abcdef"
  3. 3 String str2 = str.toUpperCase();//str2 = "ABCDEF"

6.字符串字符的替换
public String replace(charSequence oldString, charSequence newString)//用字符newString替换当前字符串中所有的oldstring字符,并返回一个新的字符串。charSequence可以为char,也可以为string。

  1. String str = "Hello";
  2. String str1 = str.replace('o','L');//str1 = "hellL"
  3. 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位置向前查找。

  1. String str = "Hello world!";
  2. int a = str.indexOf('l');//a = 2
  3. int b = str.indexOf("llo");//b = 2
  4. int c = str.indexOf("w",2);//c = 6
  5. int d = str.lastIndexOf("o");//d = 7
  6. int e = str.lastIndexOf("d",3);//e = -1

8.截去字符串两端的空格

String trim();

  1. String str = " a sd ";
  2. String str1 = str.trim();
  3. int a = str.length();//a = 6
  4. int b = str1.length();//b =

9.判断字符串是否以suffix串开头或结尾

1)boolean statWith(String suffix)判断字符串是否以suffix串开头

2)boolean endWith(String suffix)判断字符串是否以suffix串结尾

  1. 1 String str = "asdfgh";
  2. 2 boolean a = str.statWith("as");//a = true
  3. 3 boolean b = str.endWith("gh");//b = true

10.将str作为分隔符进行字符串分解

String[] split(String str)

  1. String str = "asd!qwe|zxc#";
  2. String[] str1 = str.split("!|#");//str1[0] = "asd";str1[1] = "qwe";str1[2] = "zxc";

发表评论

表情:
评论列表 (有 0 条评论,388人围观)

还没有评论,来说两句吧...

相关阅读