子字符串在 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
广告内容
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP