iT邦幫忙

0

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

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言