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";

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值