📜  Java字符串之-substring()(1)

📅  最后修改于: 2023-12-03 15:32:03.303000             🧑  作者: Mango

Java字符串之-substring()

在Java中,字符串是一种非常重要的数据类型。字符串类提供了许多有用的方法来操纵字符串。其中一个非常常用的方法是 substring()

什么是 substring() 方法?

substring() 方法用于从字符串中提取子串。您可以指定要提取的子串的起始和结束位置。在Java中,字符串中的字符位置是从0开始计数的。例如,将字符串“Hello World”中的子串“World”提取出来,可以使用以下代码:

String str = "Hello World";
String substr = str.substring(6, 11);
System.out.println(substr);

该代码的输出将是“World”。

substring() 方法的语法

substring() 方法的语法如下:

public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)

beginIndex 参数指定了要提取的子串的起始位置。endIndex 参数(可选)指定了要提取的子串的结束位置。如果省略 endIndex,将提取从 beginIndex 到字符串结尾的所有字符。

使用 substring() 方法返回 Java 字符串

以下示例演示了如何使用 substring() 方法从Java字符串中提取子串。

String str = "Java substring example";
String substr1 = str.substring(5);
String substr2 = str.substring(5, 14);
System.out.println(substr1);
System.out.println(substr2);

输出:

substring example
substring
substring() 方法的注意事项
  • substring() 方法返回的新字符串是从其中提取的字符的副本。它不会修改原始字符串。
  • 如果 beginIndex 或 endIndex 超出字符串的范围,则会引发 IndexOutOfBoundsException 异常。
  • 如果 beginIndex 等于 endIndex,则返回空字符串。
结论

substring() 是一个强大的方法,允许您从字符串中提取子串。您可以使用它来处理字符串并将其拆分成更小的部分,这很有用。但是,为了避免引起异常,必须十分小心地指定开始和结束位置。