Java函数:在字符串中查找子串的方法
发布时间:2023-08-20 02:00:58
在Java中,我们可以使用多种方法来查找一个字符串中的子串。以下是一些常用的方法:
1. indexOf()方法:该方法返回指定子串在字符串中第一次出现的位置。如果没有找到子串,则返回-1。
例如:
String str = "Hello World";
int index = str.indexOf("World");
System.out.println(index); // 输出:6
2. lastIndexOf()方法:该方法返回指定子串在字符串中最后一次出现的位置。如果没有找到子串,则返回-1。
例如:
String str = "Hello World";
int index = str.lastIndexOf("o");
System.out.println(index); // 输出:7
3. contains()方法:该方法判断字符串中是否包含指定子串,并返回布尔值。
例如:
String str = "Hello World";
boolean contains = str.contains("World");
System.out.println(contains); // 输出:true
4. matches()方法:该方法使用正则表达式判断字符串是否匹配指定的模式,并返回布尔值。
例如:
String str = "Hello World";
boolean matches = str.matches(".*W.*");
System.out.println(matches); // 输出:true
5. startsWith()方法和endsWith()方法:这两个方法用于判断字符串是否以指定的子串开始或结束,并返回布尔值。
例如:
String str = "Hello World";
boolean startsWith = str.startsWith("Hello");
boolean endsWith = str.endsWith("World");
System.out.println(startsWith); // 输出:true
System.out.println(endsWith); // 输出:true
6. substring()方法:该方法用于提取字符串中的子串,并返回新的字符串。需要指定子串的起始位置和结束位置(可选)。
例如:
String str = "Hello World"; String substr = str.substring(6); System.out.println(substr); // 输出:World
这些方法可以帮助我们在字符串中查找子串。根据具体的需求和场景选择合适的方法,可以更方便地操作字符串。
