Java中关于substring()函数的相关用法及源码

最近在LeetCode刷题,遇到一些关于字符串操作的题,算是比较基础的,可以调用函数直接解决,所以就在这写写一些关于这些函数的用法。

今天写的是关于substring()函数

这个函数有两个用法:

①substring(int beginIndex):返回一个从beginIndex开始截取的新的字符串。

用法如下:

public class Demo01 {
	public static void main(String args[]) {	
	    String str1="hello java";
	    String str2=str1.substring(6);
	    System.out.println(str2);
	}
}

输出结果为:java

在了解完之后可以查看源码,进行更深的了解,源码为:

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);
    }

观察源码可以看出,当传入的参数小于0或者大于原字符串的长度时,会报出字符串的指引越界。

②substring(int beginIndex, int endIndex):返回一个从beginIndex(包含beginIndex),endIndex(不包含endIndex)结束的新字符串。

举个例子

public class Demo01 {
	public static void main(String args[]) {	
	String str1="hello java";
	String str2=str1.substring(6,8);
	System.out.println(str2);
	}
}

输出:ja
查下源码了解一下原理

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);
    }

与一个用法大同小异。

关于substring()这个函数的用法就讲到这了,下面我写一下在LeetCode遇到的那道题。
原题如下:

字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。

代码也十分简单

class Solution {
    public String reverseLeftWords(String s, int n) {
        return s.substring(n)+s.substring(0,n);

    }
}

具体实现也很简单

public class Demo01 {
	public static void main(String args[]) {	
		Solution solution=new Solution();
		System.out.println(solution.reverseLeftWords("hello,java",6));
	}
}

输出:javahello,

今天的内容虽然比较基础,但是也算是一个小知识,所谓积少成多,慢慢的积累,懂得也会更加,继续加油鸭!!!
小伙伴们如果在Java编程上有什么疑问的都可以跟我分享鸭,大家一起进步!!!冲冲冲!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值