字符串截取相关样例

例一:

String.indexOf(String x):字符串x在字符串中第一次出现的下表索引,若不存在“x”,就返回-1

String.substring(int beginindex):从字符串索引为beginindex開始截取,包含该索引

String str = "陕西省|西安市|雁塔区";
System.out.println(str.indexOf("|"));//输出3
System.out.println(str.substring(str.indexOf("|")+1));//输出为“西安市|雁塔区”,把“陕西省|”接去掉

例二:

String str="abc.ABC.aaa";
System.out.println("'.'在str字符串中第一次出现位置的索引为:"+str.indexOf("."));
System.out.println("截取abc的值"+str.substring(0, str.indexOf(".")));
System.out.println("截取中间ABC的值:"+str.substring(str.indexOf(".")+1,str.lastIndexOf(".")));
System.out.println("截取aaa的值:"+str.substring(str.lastIndexOf(".")+1));

例三:

String path="http://localhost:8080/Client/index.jsp";
//将最后一个斜杠后,'.'曾经的部分(也就是'index')截取出来
String x = path.substring(path.lastIndexOf("/")+1, path.lastIndexOf("."));
System.out.println(x);



原文地址:https://www.cnblogs.com/lcchuguo/p/4005948.html