子字串在 Java 中是什麼意思?


java.lang 包的 String 類表示一組字元。Java 程式中的所有字串文字,例如 "abc",都實現為此類的例項。字串索引是一個整數,表示字串中每個字元的位置,從零開始。

子字串是字串的一部分/片段。你可以使用 String 類的 substring() 方法標識字串的子字串。此方法有兩種變體 −

substring(int beginIndex)

此方法接受一個整數值,表示當前字串中的一個索引,並返回從給定索引到字串末尾的子字串。

例如

即時演示

import java.util.Scanner;
public class SubStringExample {
   public static void main(String[] args) {
      System.out.println("Enter a string: ");
      Scanner sc = new Scanner(System.in);
      String str = sc.nextLine();  

      System.out.println("Enter the index of the substring: ");
      int index = sc.nextInt();          
      String res = str.substring(index);
      System.out.println("substring = " + res);
   }
}

輸出

Enter a string:
Welcome to Tutorialspoint
Enter the index of the string:
11
substring = Tutorialspoint

substring(int beginIndex, int endstring)

此方法接受兩個整數值,表示當前字串的索引值,並返回指定索引值之間的子字串。

例如

即時演示

import java.util.Scanner;
public class SubStringExample {
   public static void main(String[] args) {
      System.out.println("Enter a string: ");
      Scanner sc = new Scanner(System.in);
      String str = sc.nextLine();  
      System.out.println("Enter the start index of the substring: ");
      int start = sc.nextInt();      
      System.out.println("Enter the end index of the substring: ");
      int end = sc.nextInt();  
      String res = str.substring(start, end);
      System.out.println("substring = " + res);
   }
}

輸出

Enter a string:
hello how are you welcome to Tutorialspoint
Enter the start index of the substring:
10
Enter the end index of the substring:
20
substring = are you we

更新於: 2021 年 2 月 5 日

122 次瀏覽

Kickstart 職業生涯

學習課程並獲得認證

開始學習
廣告內容
© . All rights reserved.