MartinYeung
MartinYeung

Love life Love IT IT blog: https://ithelp.ithome.com.tw/users/20119569

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) );
//返回值: engard

		System.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


CC BY-NC-ND 2.0 版权声明

喜欢我的文章吗?
别忘了给点支持与赞赏,让我知道创作的路上有你陪伴。

加载中…

发布评论