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

Java中的字符串查找函数有哪些?如何使用?

发布时间:2023-07-02 00:59:29

在Java中,常用的字符串查找函数有以下几种:

1. indexOf()函数:该函数用于查找指定字符或字符串在原字符串中 次出现的位置。使用方法为:原字符串.indexOf(要查找的字符或字符串)。如果找到了指定的字符或字符串,则返回其在原字符串中的索引值;如果未找到,则返回-1。示例代码如下:

String str = "Hello, world!";
int index = str.indexOf("world");
System.out.println("The index of 'world' is: " + index);

2. lastIndexOf()函数:该函数用于查找指定字符或字符串在原字符串中最后一次出现的位置。使用方法与indexOf()相似,示例代码如下:

String str = "Hello, world!";
int index = str.lastIndexOf("o");
System.out.println("The index of last 'o' is: " + index);

3. contains()函数:该函数用于判断原字符串是否包含指定的字符或字符串。使用方法为:原字符串.contains(要查找的字符或字符串)。如果原字符串包含了指定的字符或字符串,则返回true;否则返回false。示例代码如下:

String str = "Hello, world!";
boolean isContains = str.contains("world");
System.out.println("The string contains 'world' is: " + isContains);

4. startsWith()函数和endsWith()函数:startsWith()函数用于判断原字符串是否以指定的字符或字符串开头,endsWith()函数用于判断原字符串是否以指定的字符或字符串结尾。使用方法为:原字符串.startsWith(要查找的字符或字符串)和原字符串.endsWith(要查找的字符或字符串)。两个函数都返回一个boolean类型的值,示例代码如下:

String str = "Hello, world!";
boolean isStartsWith = str.startsWith("Hello");
boolean isEndsWith = str.endsWith("world!");
System.out.println("The string starts with 'Hello' is: " + isStartsWith);
System.out.println("The string ends with 'world!' is: " + isEndsWith);

5. matches()函数:该函数用于通过正则表达式来匹配原字符串。使用方法为:原字符串.matches(正则表达式)。如果原字符串与正则表达式匹配,则返回true;否则返回false。示例代码如下:

String str = "Hello, world!";
boolean isMatches = str.matches("[A-Za-z]+");
System.out.println("The string matches with '[A-Za-z]+' is: " + isMatches);

上述函数只是常用的一部分,Java中还有许多其他的字符串查找函数,如split()、substring()以及正则表达式相关的一系列函数等。通过灵活运用这些字符串查找函数,可以方便地在Java中对字符串进行各种查找操作。