截取字符串获取子字符串
- 方法一通过substring方法解决
- 方法二通过split方法解决
- 方法三通过正则表达式解决
示例1
package com.yubai;
/**
* Created by bayu on 9/13/2017.
*/
public class string {
public static void main(String[] args) {
//定义字符串
String str = "hello world!";
//获取字符串的长度
System.out.println(str.length());
//截取子字符串
System.out.println(str.substring(1, 3));
//截取子字符串
System.out.println(str.substring(3));
//截取子字符串,长度大于或者为负数,则抛异常--IndexOutOfBoundsException
// System.out.println(str.substring(123));
// System.out.println(str.substring(-1));
}
}
运行结果:
12
el
lo world!
示例2
需求:把”01:大汽车”,分成01和大汽车
方法一:通过substring方法解决
package com.yubai;
/**
* Created by bayu on 9/13/2017.
*/
public class subString {
public static void main(String[] args) {
String str = " 01:大汽车 ";
String L = "";
String N = "";
int strLength = str.length();
for (int i = 0; i < strLength; i++) {
if(str.substring(i, i + 1).equals(":")){
L = str.substring(0,i).trim();
N = str.substring(i+1,strLength).trim();
}
}
System.out.println(L);
System.out.println(N);
}
}
方法二:通过split方法解决
package com.yubai;
/**
* Created by bayu on 9/13/2017.
*/
public class split {
public static void main(String[] args) {
String str = " 01:??? ";
String[] strArray = str.split(":");
System.out.println(strArray[0].trim());
System.out.println(strArray[1].trim());
}
}
方法三:通过正则表达式解决
package com.yubai;
/**
* Created by bayu on 9/12/2017.
*/
public class Test {
public static void main(String[] args) {
String str = "one123";
String regex = "(?<=one)(?=123)";
String[] strs = str.split(regex);
for (int i = 0; i < strs.length; i++) {
System.out.printf("strs[%d] = %s%n", i, strs[i]);
}
}
}
StringUtils.substringBefore(“dskeabcee”, “e”);
/结果是:dsk/
这里是以第一个”e”,为标准。
StringUtils.substringBeforeLast(“dskeabcee”, “e”)
结果为:dskeabce
这里以最后一个“e”为准。