在对字符串的处理当中我们经常会遇到从0到第n个字符的截取要求,或者是从第n个字符截取到最后,
例如:截取url中的ip和端口号,下面就来编写一个小demo吧
public static void main(String[] args) {
System.out.println(getbatchId("https://localhost:4040/jobs","/", 3));
}
public static String getbatchId(String str,String symbol, int n) {
int i = 0;
int s = 0;
while (i++ < n) {
s = str.indexOf(symbol, s + 1);
if (s == -1) {
return str;
}
}
return str.substring(0,s);//结果:https://localhost:4040
//return str.substring(s+1);//结果:jobs
}