亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> java

Java String.contains() 方法:检查子字符串是否存在(实战示例)

Java String.contains() 方法:检查子字符串是否存在

Java 中 String.contains() 方法判断指定字符序列是否出现在字符串中。存在返回 true,否则 false。因返回布尔值,常直接用于 if 语句。

方法签名

public boolean contains(CharSequence s)

参数
s —— 要搜索的字符序列。

返回值
包含指定序列返回 true,否则 false。

异常
参数 s 为 null 抛出 NullPointerException。

实战示例

下面完整示例演示常用模式并突出大小写敏感性。

public class SampleString { public static void main(String[] args) { String strSample = "This is a String contains Example"; // 检查各种子串 System.out.println("Contains 'ing': " + strSample.contains("ing")); System.out.println("Contains 'Example': " + strSample.contains("Example")); System.out.println("Contains 'example': " + strSample.contains("example")); // 大小写敏感 System.out.println("Contains 'is String': " + strSample.contains("is String")); } }

输出:

Contains 'ing': true
Contains 'Example': true
Contains 'example': false
Contains 'is String': false

何时使用 contains()

需验证子串是否存在于大字符串时使用。常见场景:

在条件语句中使用 contains()

方法与 if/else 无缝集成。简例:

public class IfExample { public static void main(String[] args) { String text = "Java string contains If else Example"; if (text.contains("example")) { System.out.println("The keyword :example: is found in the given string"); } else { System.out.println("The keyword :example: is not found in the string"); } } }

输出:

The keyword :example: is not found in the string

java

  1. Python strip() 方法完全指南:去除首尾空白与自定义字符实战
  2. Python len() 函数实战指南:测量字符串、列表、元组、字典等对象长度
  3. Python 字符串 find() 方法完全指南:语法、参数、替代方案与计数技巧
  4. Java String length() 方法:获取字符串长度(示例)
  5. 精通 Java String.indexOf():定位子字符串与实战示例
  6. Java String.charAt() 详解:语法、返回类型、异常与实战示例
  7. 精通 Java String compareTo():语法、用例与实战示例
  8. 精通 Java String.endsWith():检查字符串后缀(示例)
  9. Java 字符串替换大全:replace()、replaceAll() 与 replaceFirst() 详解
  10. Java BufferedReader 读取文件:实战指南与示例
  11. Java 插入排序算法详解:核心原理、完整代码与步骤演示
  12. Java 选择排序详解:核心原理、完整代码与步骤演示