Java 字符串截取

1. split()+正则表达式

将正则传入split()。返回的是一个字符串数组类型。这种方式截取会有很大的性能损耗,因为分析正则非常耗时。

        String str = "app-hello-world";
        String[] strs = str.split("-");
        for (String s:strs) {
            System.out.println(s);
        }
        
        结果:
        app
        hello
        world
2. subString()根据传入索引值截取

可以有不用的传入参数来提供不同的截取方式(索引从0开始)

2.1 一个参数

传入1,从1开始到结束

        String str = "app-hello-world";
        str.substring(1)
        
        结果:
        pp-hello-world
2.2 二个参数

从索引0开始,3结束(但是不包括3)

        String str = "app-hello-world";
        str.substring(0,3)
        
        结果:
        app
3. StringUtils方法

根据参数截取字符串

        String str = "app-hello-world";
        
        //截取str中的最后一个“-”之前的字符串
        StringUtils.substringBefore(str, "-"); 
        
        //截取str中的最后一个“-”之前的字符串
        StringUtils.substringBeforeLast(str, "-"); 
        
        结果:
        app
        app-hello
4.拓展方法,截取任意字符串之前或之后的字符串
(字符串中有相同的字段,如:app-hello-world)

        String str = "app-hello-world";
        //字符串中第一个出现"-"的索引
        int beginIndex = str.indexOf("-");
        //字符串中最后一个出现"-"的索引
        int endIndex = str.lastIndexOf("-");
        
        //截取指定字符前的字符
        System.out.println(str.substring(0,beginIndex));
        //截取指定字符之后的字符
        System.out.println(str.substring(beginIndex + 1));

        //截取最后一个出现字符前的字符串
        System.out.println(str.substring(0,endIndex));
        //截取最后一个出现字符后的字符串
        System.out.println(str.substring(endIndex + 1));

        //截取俩个特定字符串中间的字段
        System.out.println(str.substring(beginIndex + 1,endIndex));
        
        结果:
        app
        hello-world
        
        app-hello
        world
        
        hello
        

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值