Java中的子字符串是什么?

包的String类java.lang表示字符集。Java程序中的所有字符串文字(例如“ abc”)都实现为此类的实例。字符串索引是一个整数,表示每个字符在字符串中从零开始的位置。

是字符串的一部分/段。您可以使用substring()String类的方法标识字符串的子字符串。此方法有两个变体-

substring(int beginIndex)

此方法接受表示当前字符串中索引的整数值,并返回从给定索引开始到字符串末尾的子字符串。

示例

import java.util.Scanner;
public class SubStringExample {
   public static void main(String[] args) {
      System.out.println("输入一个字符串: ");
      Scanner sc = new Scanner(System.in);
      String str = sc.nextLine();  

      System.out.println("输入子字符串的索引: ");
      int index = sc.nextInt();          
      String res = str.substring(index);
      System.out.println("substring = " + res);
   }
}
输出结果
输入一个字符串:
Welcome to Nhooo
Enter the index of the string:
11
substring = Nhooo

substring(int beginIndex, int endstring)

此方法接受表示当前字符串的索引值的两个整数值,并返回给定索引值之间的子字符串。

示例

import java.util.Scanner;
public class SubStringExample {
   public static void main(String[] args) {
      System.out.println("输入一个字符串: ");
      Scanner sc = new Scanner(System.in);
      String str = sc.nextLine();  
      System.out.println("输入子字符串的起始索引: ");
      int start = sc.nextInt();      
      System.out.println("输入子字符串的结束索引: ");
      int end = sc.nextInt();  
      String res = str.substring(start, end);
      System.out.println("substring = " + res);
   }
}
输出结果
输入一个字符串:
hello how are you welcome to Nhooo
输入子字符串的起始索引:
10
输入子字符串的结束索引:
20
substring = are you we