关于java substring()的注意事项

本文详细探讨了Java中substring()方法的使用,包括其两种调用方式及可能出现的陷阱。例如,当只传入一个参数时,substring()会从指定位置到字符串末尾。而当传入两个参数时,注意它是左闭右开的区间。特别地,当传入的结束索引等于字符串长度时,结果为空字符串。通过分析源码,解释了为何`a.substring(a.length())`返回空字符串的原因。
摘要由CSDN通过智能技术生成

关于java substring()的注意事项

用了好久的s.substring();今天突然发现还有一些坑之前不知道。先列举一下substring()的三种用法。

  1. a.substring(start,end);
public class test01 {
    public static void main(String[] args) {
        String a="abcdef";
        System.out.println(a.substring(0,2));
        System.out.println(a.substring(0,a.length()));
    }
}

输出结果1:ab
输出结果2 : abcdef
注意点1:当为两个参数时,参数为下标索引,并且为左闭右开。右边界可以为a.length()。

  1. a.substring(start);
public class test01 {
    public static void main(String[] args) {
        String a="abcdef";
        System.out.println(a.substring(0));
        System.out.println(a.substring(1));
    }
}

输出结果1:abcdef
输出结果2 : bcdef

  1. 以上几点其实答主之前都是会的,今天在做算法题的时候遇到的另一种情况,具体题目就不贴了,我把其中我关于substring困惑的地方贴出来,供大家注意。
public class test01 {
    public static void main(String[] args) {
        String a="abcdef";
        System.out.println(a.substring(a.length()));
    }
}

我第一反应这样的写法是错误的,应该是error,因为我一直认为,左参数一定是要小于a.length()的,但是这个的输出结果是空字符串,后来我看了一下源码,向大家解释一下

public String substring(int beginIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        int subLen = value.length - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
    }
public String substring(int beginIndex, int endIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        if (endIndex > value.length) {
            throw new StringIndexOutOfBoundsException(endIndex);
        }
        int subLen = endIndex - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        return ((beginIndex == 0) && (endIndex == value.length)) ? this
                : new String(value, beginIndex, subLen);
    }

总结来说,无论是一个参数还是两个参数,参数的范围是0<=start<=end<=a.length();一个参数的a.substring(start)等于a.substring(start,a.length()),同理,上述System.out.println(a.substring(a.length()));可以写成System.out.println(a.substring(a.length(),a.length()));根据左闭右开,所以是空字符串。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值