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

Java函数实现字符串搜索

发布时间:2023-07-24 17:40:37

在Java中,可以通过调用String类的一些方法来实现字符串搜索。

1. indexOf方法:

这个方法可以用来查找指定字符或子字符串在字符串中的 个出现位置。它的使用方式是调用String类的indexOf方法,传入要搜索的字符或子字符串作为参数,返回它在字符串中的位置。如果找不到该字符或子字符串,则返回-1。

示例代码:

   String str = "Hello, World!";
   int index = str.indexOf("World");
   System.out.println("字符或子字符串的位置是:" + index); // 输出:字符或子字符串的位置是:7
   

2. lastIndexOf方法:

这个方法可以用来查找指定字符或子字符串在字符串中的最后一个出现位置。它的使用方式和indexOf方法类似,只不过它是在字符串中从后往前搜索。

示例代码:

   String str = "Hello, World!";
   int lastIndex = str.lastIndexOf("o");
   System.out.println("字符或子字符串的最后位置是:" + lastIndex); // 输出:字符或子字符串的最后位置是:9
   

3. contains方法:

这个方法可以用来检查一个字符串是否包含指定的子字符串。它的使用方式是调用String类的contains方法,传入要搜索的子字符串作为参数,返回一个boolean值,表示是否包含。

示例代码:

   String str = "Hello, World!";
   boolean contains = str.contains("World");
   System.out.println("字符串是否包含指定的子字符串:" + contains); // 输出:字符串是否包含指定的子字符串:true
   

4. matches方法:

这个方法可以用来检查一个字符串是否与指定的正则表达式匹配。它的使用方式是调用String类的matches方法,传入要匹配的正则表达式作为参数,返回一个boolean值,表示是否匹配。

示例代码:

   String str = "Hello, World!";
   boolean matches = str.matches("He.*");
   System.out.println("字符串是否与指定的正则表达式匹配:" + matches); // 输出:字符串是否与指定的正则表达式匹配:true
   

5. startsWith和endsWith方法:

这两个方法可以用来检查一个字符串是否以指定的字符或子字符串开头或结尾。它们的使用方式是调用String类的startsWith和endsWith方法,传入要检查的字符或子字符串作为参数,返回一个boolean值,表示是否符合条件。

示例代码:

   String str = "Hello, World!";
   boolean startsWith = str.startsWith("Hello");
   boolean endsWith = str.endsWith("!");
   System.out.println("字符串是否以指定字符或子字符串开头:" + startsWith); // 输出:字符串是否以指定字符或子字符串开头:true
   System.out.println("字符串是否以指定字符或子字符串结尾:" + endsWith); // 输出:字符串是否以指定字符或子字符串结尾:true
   

除了以上这些方法,还可以使用正则表达式和循环等方式来实现更复杂的字符串搜索。在实际场景中,根据需求选择适合的方法可以更快、更准确地搜索字符串。