substring
返回一个新的字符串,它是此字符串的一个子字符串。该子字符串始于指定索引处的字符,一直到此字符串索引末尾,用于截取字符串的某部分。
1. 截取某个字符之前或者之后的字符串
实现内容:
实现代码:
方法1:Java自带的方法
@Test
void testSub() {
String sub = "/nas/file/OCR/testOcr";
System.out.println(">>>>截取之前的字符:" + sub);
String appoint = "OCR";
System.out.println(">>>>截取的字符:" + appoint);
// 截取 OCR之前的字符串
if (sub != null && sub.contains(appoint)) {
String before = sub.substring(0, sub.indexOf(appoint));
// 结果:/nas/file/
System.out.println(">>>>截取" + appoint + "之前的字符:" + before);
}
// 截取 OCR之后的字符串
if (sub != null && sub.contains(appoint)) {
String beforeSub = sub.substring(0, sub.indexOf(appoint));
String after = sub.substring(beforeSub.length() + appoint.length());
// 结果:/testOcr
System.out.println(">>>>截取" + appoint + "之后的字符:" + after);
}
}
方法2:Hutool工具类官网地址 :https://hutool.cn/docs/index.html#/
maven依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.9</version>
</dependency>
@Test
void testSub() {
String sub = "/nas/file/OCR/testOcr";
System.out.println(">>>>截取之前的字符:" + sub);
String appoint = "OCR";
System.out.println(">>>>截取的字符:" + appoint);
String subBefore = StrUtil.subBefore(sub, appoint, true);
System.out.println(">>>>截取" + appoint + "之前的字符:" + subBefore);
String subAfter = StrUtil.subAfter(sub, appoint, true);
System.out.println(">>>>截取" + appoint + "之后的字符:" + subAfter);
}