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

如何使用Java函数查找字符串中的子字符串?

发布时间:2023-06-26 01:22:07

在Java中,有许多方法可以用来查找一个字符串中包含的子字符串。这些方法可以被用来解决不同的问题和场景,每个方法都有其优点和局限性。

1. indexOf() 方法

indexOf() 方法是 Java 中最基本的字符串查找方法之一。此方法可返回子字符串在原始字符串中首次出现的位置,如果没有找到,则返回 -1。

语法:int indexOf(int ch) 或 int indexOf(String str)

其中 ch 为要查找的字符,str 为要查找的字符串。

示例:

String str = "Hello World";

int index = str.indexOf("World");

System.out.println("Index of World in str is: " + index);

输出:

Index of World in str is: 6

2. lastIndexOf() 方法

lastIndexOf() 方法与 indexOf() 方法十分相似,但是从原始字符串的末尾开始查找。此方法可返回子字符串在原始字符串中最后一次出现的位置,如果没有找到,则返回 -1。

语法:int lastIndexOf(int ch) 或 int lastIndexOf(String str)

其中 ch 为要查找的字符,str 为要查找的字符串。

示例:

String str = "Hello World";

int index = str.lastIndexOf("World");

System.out.println("Index of World in str is: " + index);

输出:

Index of World in str is: 6

3. contains() 方法

contains() 方法可用来检查字符串中是否包含指定的子字符串。如果原始字符串中包含子字符串,此方法返回 true,否则返回 false。

语法:boolean contains(CharSequence s)

其中 s 为要查找的子字符串。

示例:

String str = "Hello World";

boolean contains = str.contains("World");

System.out.println("str contains World: " + contains);

输出:

str contains World: true

4. startsWith() 和 endsWith() 方法

startsWith() 方法可用来检查字符串是否以指定的子字符串开头,而 endsWith() 方法则是检查字符串是否以指定的子字符串结尾。

语法:boolean startsWith(String prefix) 或 boolean endsWith(String suffix)

其中 prefix 和 suffix 分别为要查找的开头或结尾子字符串。

示例:

String str = "Hello World";

boolean startsWith = str.startsWith("Hello");

boolean endsWith = str.endsWith("World");

System.out.println("str starts with Hello: " + startsWith);

System.out.println("str ends with World: " + endsWith);

输出:

str starts with Hello: true

str ends with World: true

5. matches() 方法

matches() 方法可用来检查字符串是否与指定的正则表达式匹配。如果字符串与正则表达式匹配,此方法返回 true,否则返回 false。

语法:boolean matches(String regex)

其中 regex 为要匹配的正则表达式。

示例:

String str = "123456";

boolean matches = str.matches("\\d+");

System.out.println("str matches \\d+: " + matches);

输出:

str matches \d+: true

总结:

以上是Java中一些常用的查找字符串中子字符串的方法,我们可以根据实际需求选择合适的方法。需要注意的是,在使用某些方法时,可能需要考虑到字符大小写等因素,以免影响方法的准确性。