Java截取字符串的常见方法

在项目中经常会遇到截取字符串的需求,这里重点介绍两种常见的截取字符串方法。

方法一:通过split()

将正则传入split()。返回的是一个字符串数组类型。不过通过这种方式截取会有很大的性能损耗,因为分析正则非常耗时。

String str = "[email protected]";
String[] strs = str.split("@");
for(int i=0,i<strs.length;i++){
    System.out.println(strs[i].toString());
}

运行结果:

53285964
qq.com

方法二:通过subString()方法来进行字符串截取

1、只传一个参数:subString(int beginIndex)

将字符串从索引号为beginIndex开始截取,一直到字符串末尾。(注意索引值从0开始);

String sb = "asdfghj";
String str = sb.substring(2);
System.out.println(str);

运行结果:

dfghj
2、传入两个参数:substring(int beginIndex, int endIndex)

从索引号beginIndex开始到索引号endIndex结束(返回结果包含索引为beginIndex的字符不包含索引我endIndex的字符),如下所示:

String sb = "[email protected]";
String str = sb.substring(0, 8);
System.out.println(str);

运行结果

53285964
3、根据某个字符截取字符串

这里根据”@”截取字符串(也可以是其他子字符串)

String sb = "[email protected]";
String str = sb.substring(0, sb.indexOf("@"));
System.out.println(str);

运行结果:

53285964

分析:indexOf(String str)方法返回的是子字符串第一次出现在字符串的索引位置,上面的代码返回的是@前面的字符。

猜你喜欢

转载自blog.csdn.net/zjx2016/article/details/74557301