如何在Java中判断一个字符串是否包含另一个字符串
2024-07-30
65
在Java中,可以使用contains()方法或matches()方法来判断一个字符串是否包含另一个字符串。
一、使用contains()方法
Java中的contains()方法用于检查原字符串(调用方法的字符串)是否包含特定的字符序列。如果原字符串包含指定的字符序列,则返回true,否则返回false。
public class Main { public static void main(String[] args) { String str = "Hello, World!"; String subStr = "World"; boolean isContains = str.contains(subStr); System.out.println(isContains); // 输出:true } }
这种方法适合于简单的字符序列检查,不涉及正则表达式的匹配。
二、使用matches()方法
如果需要频繁使用正则表达式来检查,那么我们可以使用String类的matches()方法。
public class Main { public static void main(String[] args) { String str = "Hello, World!"; String regex = ".*World.*"; boolean isMatch = str.matches(regex); System.out.println(isMatch); // 输出:true } }
matches()方法会根据传入的正则表达式返回匹配结果,如果字符串匹配给定的正则表达式则返回true,否则返回false。
三、综合应用
在实际开发中,可能会遇到比较复杂的情况,比如可能要查找的字符序列事先是未知的,或者需要检查多个字符序列等等。在这种情况下,可以结合使用contains()方法和matches()方法来满足需求。
public class Main { public static void main(String[] args) { String str = "Hello, World!"; String[] subStrs = {"Hello", "Java", "World"}; for (String subStr : subStrs) { if (str.contains(subStr)) { System.out.println("The string contains " + subStr); } else { System.out.println("The string does not contain " + subStr); } } } }
代码中的字符串数组包含了我们想要检查的所有字符序列,使用一个for-each循环对每个字符序列进行检查,如果原字符串包含当前字符序列,就打印出相应的信息。
更新于:3个月前赞一波!
相关文章
- 【说站】java数组怎么定义
- 【说站】java之JVM的字节码结构
- 【说站】java条件运算符是什么
- 【说站】java如何创建对象数组
- 【说站】java随机打乱数组顺序
- 【说站】java集合和数组的区别
- 【说站】java中instanceof运算符是什么
- 【说站】Java集合框架Arrays的介绍
- 【说站】java反射机制原理详解
- 【说站】java环境变量配置path
- 【说站】java中@Inherited是什么?
- 【说站】java位运算符的应用范围
- 【说站】java中@Retention是什么?
- 【说站】java全栈是什么意思
- 【说站】cmd配置java环境变量
- 【说站】java @Documented怎么用?
- 【说站】java注解有什么作用
- 【说站】java短路逻辑运算符是什么
- 【说站】java自增自减运算符有哪些?
- 【说站】java自定义注解是什么?
文章评论
评论问答