如何使用Java中的String类的substring()函数?
Java中的String类是Java语言中最常使用的类之一。它提供了许多有用的函数来处理字符串,其中之一就是substring()函数。该函数用于从一个字符串中获取子字符串。
substring()函数的语法如下:
public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)
个substring()函数接受一个整数参数beginIndex,并返回一个字符串,该字符串从beginIndex开始,到字符串的结尾处。例如,以下代码将输出"world":
String str = "Hello world";
String subStr = str.substring(6);
System.out.println(subStr);
第二个substring()函数接受两个整数参数beginIndex和endIndex,并返回一个字符串,该字符串从beginIndex开始,并在endIndex处结束。例如,以下代码将输出"wor":
String str = "Hello world";
String subStr = str.substring(6, 9);
System.out.println(subStr);
需要注意的是,substring()函数返回的字符串是从原始字符串的子串中复制而来的。因此,对返回的字符串所做的任何更改都不会影响原始字符串。
以下是一些使用子串函数的示例:
1.获取文件名的扩展名
String filename = "example.pdf";
String extension = filename.substring(filename.lastIndexOf(".") + 1);
System.out.println(extension); // output: "pdf"
2. 从URL中获取主机名
String url = "https://www.google.com/search?q=java";
int start = url.indexOf("//") + 2;
int end = url.indexOf("/", start);
String host = url.substring(start, end);
System.out.println(host); // output: "www.google.com"
3. 将字符串分割成两个部分
String str = "Hello, world!";
int index = str.indexOf(",");
String firstPart = str.substring(0, index);
String secondPart = str.substring(index + 1);
System.out.println(firstPart); // output: "Hello"
System.out.println(secondPart); // output: " world!"
总之,Java的String类的substring()函数是一个非常有用的函数,可以帮助我们从字符串中获取子串。请记住,该函数返回的字符串是与原始字符串无关的。
