欢迎访问宙启技术站
智能推送

Java函数:如何在字符串中查找子串?

发布时间:2023-06-18 17:27:59

Java是一门流行的面向对象编程语言,它提供了强大的字符串处理功能,可以轻松地在字符串中查找子串。

Java中查找子串的常用方法有:

1. indexOf()方法:这个方法返回整个字符串中第一个匹配子串的索引。如果子串不存在,则返回-1。

语法:indexOf(String str)

示例:

String str = "hello world";
int index = str.indexOf("world");
if (index != -1) {
    System.out.println("子串存在,索引为:" + index);
} else {
    System.out.println("子串不存在");
}

输出结果:

子串存在,索引为:6

2. substring()方法:这个方法返回整个字符串中从指定位置开始的子串。

语法:substring(int beginIndex)

示例:

String str = "hello world";
String subStr = str.substring(6);
System.out.println("子串为:" + subStr);

输出结果:

子串为:world

3. contains()方法:这个方法返回整个字符串是否包含指定的子串。

语法:contains(CharSequence s)

示例:

String str = "hello world";
boolean isContain = str.contains("orl");
if (isContain) {
    System.out.println("字符串包含子串");
} else {
    System.out.println("字符串不包含子串");
}

输出结果:

字符串包含子串

4. lastIndexOf()方法:这个方法返回整个字符串中最后一个匹配子串的索引。如果子串不存在,则返回-1。

语法:lastIndexOf(String str)

示例:

String str = "hello world";
int lastIndex = str.lastIndexOf("o");
if (lastIndex != -1) {
    System.out.println("最后一个匹配子串的索引为:" + lastIndex);
} else {
    System.out.println("子串不存在");
}

输出结果:

最后一个匹配子串的索引为:7

除了上述方法外,Java还提供了正则表达式的功能,可以更加灵活的查找字符串中的子串。

示例:

String str = "hello world";
String pattern = "world";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(str);
if (m.find()) {
    System.out.println("子串存在");
} else {
    System.out.println("子串不存在");
}

输出结果:

子串存在

总结:

Java提供了多种方法来查找字符串中的子串,可以根据具体需求选择适合的方法。对于简单的子串查找,可以使用indexOf()和contains()方法;对于需要截取指定位置的子串,可以使用substring()方法;对于复杂的查找,可以使用正则表达式来处理。