This is a more commonly used method.
This method has two forms:
substring(int beginIndex); //提取从索引位置开始至结尾处的字符串部分 substring(int beginIndex,int endIndex); //提取beginIndex开始到endIndex的字符串部分
Instance code:
String str = "你好,Java练习生"; //substring(int beginIndex); String substring1 = str.substring(3); //substring(int beginIndex,int endIndex); String substring2 = str.substring(3, 7); System.out.println(substring1);//Java练习生 System.out.println(substring2);//Java
It should be noted that:The counting starts from 0, if it exceeds the character If the string length is too long, an error will be reported:
java.lang.StringIndexOutOfBoundsException: String index out of range:
Calculation position diagram
##2 split() regular expression is not commonly used, but in certain Especially useful in certain situations. Format:String.split("specify delimiter");–returns an array
String str = "good,good,study,day,day,up"; String[] split = str.split(","); for (String s: split) { System.out.println(s); }
com.lispcast org.apache.commons.lang 2.5.0
String str = "大家好,我是练习两年半的个人练习生,cxk"; //- String substring(String str,int start):避免异常地从指定的String获取一个子字符串。 String substring1 = StringUtils.substring(str, 4); //- String substring(String str,int start, int end):可避免异常地从指定的String获取一个子字符串。 String substring2 = StringUtils.substring(str, 4, 7); //- String substringAfter(String str,String separator):在第一次出现分隔符后获取子字符串。 String substringAfter = StringUtils.substringAfter(str, ","); //- String substringAfterLast(String str,String separator):在最后一次出现分隔符之后获取子字符串。 String substringAfterLast = StringUtils.substringAfterLast(str, ","); //- String substringBefore(String str,String separator):在第一次出现分隔符之前获取子字符串。 String substringBefore = StringUtils.substringBefore(str, ","); //- String substringBeforeLast(String str,String separator):在最后一次出现分隔符之前获取子字符串。 String substringBeforeLast = StringUtils.substringBeforeLast(str, ","); //- String substringBetween(String str,String tag):获取嵌套在同一String的两个实例之间的String。 String substringBetween1 = StringUtils.substringBetween(str, ","); // - String substringBetween(String str, String open, String close):获取嵌套在两个字符串之间的字符串。 String substringBetween2 = StringUtils.substringBetween(str, "好", "的"); System.out.println(substring1); System.out.println(substring2); System.out.println(substringAfter); System.out.println(substringAfterLast); System.out.println(substringBefore); System.out.println(substringBeforeLast); System.out.println(substringBetween1); System.out.println(substringBetween2);
The above is the detailed content of What are the methods for intercepting strings in Java?. For more information, please follow other related articles on the PHP Chinese website!