1. split()+正则表达式
将正则传入split()。返回的是一个字符串数组类型。这种方式截取会有很大的性能损耗,因为分析正则非常耗时。
String str = "app-hello-world";
String[] strs = str.split("-");
for (String s:strs) {
System.out.println(s);
}
结果:
app
hello
world
2. subString()根据传入索引值截取
可以有不用的传入参数来提供不同的截取方式(索引从0开始)
2.1 一个参数
传入1,从1开始到结束
String str = "app-hello-world";
str.substring(1)
结果:
pp-hello-world
2.2 二个参数
从索引0开始,3结束(但是不包括3)
String str = "app-hello-world";
str.substring(0,3)
结果:
app
3. StringUtils方法
根据参数截取字符串
String str = "app-hello-world";
//截取str中的最后一个“-”之前的字符串
StringUtils.substringBefore(str, "-");
//截取str中的最后一个“-”之前的字符串
StringUtils.substringBeforeLast(str, "-");
结果:
app
app-hello
4.拓展方法,截取任意字符串之前或之后的字符串
(字符串中有相同的字段,如:app-hello-world)
String str = "app-hello-world";
//字符串中第一个出现"-"的索引
int beginIndex = str.indexOf("-");
//字符串中最后一个出现"-"的索引
int endIndex = str.lastIndexOf("-");
//截取指定字符前的字符
System.out.println(str.substring(0,beginIndex));
//截取指定字符之后的字符
System.out.println(str.substring(beginIndex + 1));
//截取最后一个出现字符前的字符串
System.out.println(str.substring(0,endIndex));
//截取最后一个出现字符后的字符串
System.out.println(str.substring(endIndex + 1));
//截取俩个特定字符串中间的字段
System.out.println(str.substring(beginIndex + 1,endIndex));
结果:
app
hello-world
app-hello
world
hello