Java 中判断字符串包含97


在 Java 中,判断一个字符串是否包含另一个子字符串是一个常见的操作。这有多种方法,每种方法都有其独特的优点和缺点。

1. 使用indexOf() 方法

indexOf() 方法返回子字符串在主字符串中第一次出现的位置。如果子字符串不存在,则返回 -1。以下是如何使用 indexOf() 方法:public static void main(String[] args) {
String mainString = "Hello World";
String substring = "World";
int index = (substring);
if (index != -1) {
("子字符串存在于主字符串中");
} else {
("子字符串不存在于主字符串中");
}
}

2. 使用contains() 方法

contains() 方法返回一个布尔值,指示子字符串是否包含在主字符串中。以下是如何使用 contains() 方法:public static void main(String[] args) {
String mainString = "Hello World";
String substring = "World";
boolean isContained = (substring);
if (isContained) {
("子字符串存在于主字符串中");
} else {
("子字符串不存在于主字符串中");
}
}

3. 使用正则表达式

正则表达式是一种强大的模式匹配语言,可用于匹配文本中的模式。以下是如何使用正则表达式判断字符串是否包含另一个子字符串:public static void main(String[] args) {
String mainString = "Hello World";
String substring = "World";
boolean isContained = (".*" + substring + ".*");
if (isContained) {
("子字符串存在于主字符串中");
} else {
("子字符串不存在于主字符串中");
}
}

4. 使用containsAll() 方法

containsAll() 方法检查一个字符串是否包含一组子字符串。以下是如何使用 containsAll() 方法:public static void main(String[] args) {
String mainString = "Hello World";
List substrings = ("Hello", "World");
boolean isContainedAll = (substrings);
if (isContainedAll) {
("所有子字符串都存在于主字符串中");
} else {
("所有子字符串都不存在于主字符串中");
}
}

5. 使用equalsIgnoreCase() 方法

equalsIgnoreCase() 方法比较两个字符串,忽略大小写。以下是如何使用 equalsIgnoreCase() 方法:public static void main(String[] args) {
String mainString = "Hello World";
String substring = "hello world";
boolean isEqualToIgnoreCase = (substring);
if (isEqualToIgnoreCase) {
("子字符串与主字符串相同(忽略大小写)");
} else {
("子字符串与主字符串不同(忽略大小写)");
}
}

选择合适的方法

选择哪种方法取决于性能、灵活性和其他因素。对于简单比较,contains() 或 indexOf() 是最佳选择。对于更复杂的模式匹配,正则表达式可能是更好的选择。对于包含多个子字符串的情况,containsAll() 很有用。最后,对于大小写不敏感的比较,equalsIgnoreCase() 是最佳选择。

2024-10-28


上一篇:Java 数组动态操作指南

下一篇:Java 中的数据库编程