Java – Substring()的介绍及用法

阅读时间: 5分钟

public String substring(int beginIndex, int endIndex)
将会返回一个substring,而这个substring 的第1个index会由beginIndex 开始,最后一个index会是endIndex。
这个substring 的长度会是 endIndex-beginIndex。
这样解释会有点抽象,所以会以例子说明一下。

public String substring(int beginIndex)
将会返回一个substring,而这个substring 会由beginIndex开始,直到String的最后一个letter。不能自定义结束的位置。

这样解释会有点抽象,所以会以例子说明一下。
例子:

public class SubStringTest {    public static void main(String args[]) {        String Str = new String("uppengarden.com");         System.out.print("返回值 :" );        System.out.println(Str.substring(4) );//返回值 : engarden.com         System.out.print("返回值 :" );        System.out.println(Str.substring(4, 10) );//返回值 : engardSystem.out.print("返回值 :" );        System.out.println("uppengarden.com".substring(4, 10) );//返回值 : engard    }}

解释:
substring(int beginIndex, int endIndex)
主要有2个parameters分别是以下:
beginIndex – 开始的位置,包括当下的index。
endIndex – 结尾的位置,不包括当下的index。

会有机会出现以下的Error Exception:
IndexOutOfBoundsException

开始的index是负数结尾的index大于String的长度开始的index大于结尾的index

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章