使用Java函数进行字符串匹配
发布时间:2023-07-03 21:12:23
在Java中,我们可以使用多种方法进行字符串匹配。下面将介绍一些常用的方法。
1. equals()方法:
这是最基本的方法,用于比较两个字符串是否完全相同,区分大小写。
示例代码:
String str1 = "Hello";
String str2 = "Hello";
if (str1.equals(str2)) {
System.out.println("Strings are equal");
} else {
System.out.println("Strings are not equal");
}
2. equalsIgnoreCase()方法:
与equals()方法类似,但该方法不区分大小写。
示例代码:
String str1 = "Hello";
String str2 = "hello";
if (str1.equalsIgnoreCase(str2)) {
System.out.println("Strings are equal");
} else {
System.out.println("Strings are not equal");
}
3. contains()方法:
用于检查一个字符串是否包含另一个字符串。
示例代码:
String str1 = "Hello World";
String str2 = "World";
if (str1.contains(str2)) {
System.out.println("String contains substring");
} else {
System.out.println("String does not contain substring");
}
4. startsWith()和endsWith()方法:
分别用于检查一个字符串是否以另一个字符串开头或结尾。
示例代码:
String str1 = "Hello World";
String str2 = "Hello";
String str3 = "World";
if (str1.startsWith(str2)) {
System.out.println("String starts with substring");
} else {
System.out.println("String does not start with substring");
}
if (str1.endsWith(str3)) {
System.out.println("String ends with substring");
} else {
System.out.println("String does not end with substring");
}
5. indexOf()方法:
该方法返回指定字符串在目标字符串中第一次出现的位置索引。如果目标字符串中不包含该字符串,返回-1。
示例代码:
String str = "Hello World";
int index = str.indexOf("World");
if (index != -1) {
System.out.println("Substring found at index " + index);
} else {
System.out.println("Substring not found");
}
6. matches()方法:
该方法使用正则表达式来匹配字符串。
示例代码:
String str = "Hello";
if (str.matches("[A-Z][a-z]+")) {
System.out.println("String matches regex pattern");
} else {
System.out.println("String does not match regex pattern");
}
以上是一些常用的字符串匹配方法。根据具体的需求,我们可以选择合适的方法来实现字符串匹配功能。
