String interception method in Java

String interception in java

1. Use the subString() method to intercept the string and return the substring in the string. There are two usages in java

//示例代码
public static void main(String[] args) {
    
    
    String Str = "hello wrold";
    System.out.print("返回值,从第4位截取到字符串末尾 :" );
    System.out.println(Str.substring(4) );  //返回值,从第4位截取到字符串末尾 :   o wrold
 
    System.out.print("返回值,从第4位截取到第10位 :" );
    System.out.println(Str.substring(4, 10) );  //返回值,从第4位截取到第10位    :   o wrol  左闭右开
}

2. Intercept through the method provided by StringUtils

//与第一种方法效果一样
StringUtils.substring("hello world", 4);     // 返回值,从第4位截取到字符串末尾 : o wrold
StringUtils.substring("hello world", 4, 10); // 返回值,从第4位截取到第10位    : o wrol

//截取某个字符串之前的字符
StringUtils.substringBefore("hello world", "l"); //结果是:he    这里是以第一个“l”为标准
StringUtils.substringBeforeLast("hello world", "l"); //结果为:hello wor   这里以最后一个“l”为标准

//截取某个字符串之后的字符
StringUtils.substringAfter("hello world", "l"); //结果是:lo world    这里是以第一个“l”为标准
StringUtils.substringAfterLast("hello world", "l"); //结果为:d       这里以最后一个“l”为标准

//截取两个字符串之间的字符
StringUtils.substringBetween("hello world", "o"); //结果是: w   两个o之间的字符串   
StringUtils.substringBetween("hello world", "l", "r"); //结果是: lo wo   第一个字符“l”与第一个字符“r”之间的字符串   
StringUtils.substringsBetween("hello world", "l", "r"); //结果是: 数组 [lo wo]   第一个字符“l”与第一个字符“r”之间的字符串,以数组形式返回,需要用Arrays.toString()才能显示[lo wo],不然是地址值。

The above is the commonly used java interception string method.

Guess you like

Origin blog.csdn.net/m0_44980168/article/details/131127990