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 版权声明

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

加载中…

发布评论