一、contains 方法详解
1. 方法定义与语法
public boolean contains(charsequence s)
- 功能:检查字符串是否包含指定的字符序列
- 参数:
charsequence
类型(string 实现了该接口) - 返回值:boolean 类型(true 表示包含,false 表示不包含)
2. 底层实现原理
// string 类中的实际实现 public boolean contains(charsequence s) { return indexof(s.tostring()) >= 0; }
- 实际调用
indexof()
方法 - 如果找到子串返回索引位置(≥0),否则返回 -1
- 时间复杂度:o(n*m),n 是原字符串长度,m 是子串长度
3. 使用示例
string text = "java programming is fun"; system.out.println(text.contains("pro")); // true system.out.println(text.contains("python")); // false
4. 注意事项
- 大小写敏感:
"hello".contains("hello")
返回 false - 空字符串:
"abc".contains("")
总是返回 true - null 参数:会抛出 nullpointerexception
二、substring 方法详解
1. 方法重载
public string substring(int beginindex) public string substring(int beginindex, int endindex)
2. 参数说明
参数 | 说明 | 注意事项 |
---|---|---|
beginindex | 起始索引(包含) | 必须 ≥0 且 ≤ 字符串长度 |
endindex | 结束索引(不包含) | 必须 ≥ beginindex 且 ≤ 字符串长度 |
3. 使用示例
string str = "helloworld"; // 从索引5开始到结尾 system.out.println(str.substring(5)); // "world" // 从索引0开始到5(不包含5) system.out.println(str.substring(0, 5)); // "hello"
4. 常见错误
// 索引越界 str.substring(10); // stringindexoutofboundsexception // 参数顺序错误 str.substring(5, 0); // stringindexoutofboundsexception
三、contains 和 substring 结合使用
1. 原代码分析
public static string findsubstringwithcontext(string text, string substring) { if (text.contains(substring)) { int startindex = text.indexof(substring); int endindex = startindex + substring.length(); return text.substring(0, endindex); } return "子串未找到"; }
2. 问题诊断
- 功能不完整:只返回了子串前面的内容,没有返回后面的内容
- 描述不符:方法名暗示返回"完整前后内容",但实际只返回了前半部分
- 输出格式:没有明确区分前后文和子串本身
3. 改进实现
public static string getsubstringcontext(string text, string sub) { if (!text.contains(sub)) { return "未找到子串"; } int start = text.indexof(sub); int end = start + sub.length(); string before = (start > 0) ? text.substring(0, start) : ""; string after = (end < text.length()) ? text.substring(end) : ""; return "前文: \"" + before + "\", 子串: \"" + sub + "\", 后文: \"" + after + "\""; }
4. 测试用例
string text = "这是一个测试字符串,用于测试子串出现的完整前后内容。"; string substring = "测试"; system.out.println(getsubstringcontext(text, substring)); // 输出: 前文: "这是一个", 子串: "测试", 后文: "字符串,用于测试子串出现的完整前后内容。"
四、其他重要字符串方法详解
1. split 方法
string csv = "张三,20,男"; string[] parts = csv.split(","); // ["张三", "20", "男"]
- 正则表达式支持:
split("\\.")
按点分割 - 限制分割次数:
split(",", 2)
只分割成两部分
2. replace/replaceall
string input = "a1b2c3"; string replaced = input.replaceall("\\d", ""); // "abc"
replace
:替换字符或字符序列replaceall
:使用正则表达式替换
3. trim 和 isempty
string userinput = " hello world "; string trimmed = userinput.trim(); // "hello world" boolean empty = trimmed.isempty(); // false
trim()
:移除首尾空白字符isempty()
:检查长度是否为0
4. startswith/endswith
string filename = "document.txt"; boolean istextfile = filename.endswith(".txt"); // true
五、最佳实践与常见问题
1. 字符串操作最佳实践
- 空值检查:始终检查可能为 null 的字符串
- 索引边界:使用 substring 前验证索引范围
- 不可变性:字符串不可变,操作返回新对象
- 性能考虑:避免在循环中拼接字符串(使用 stringbuilder)
2. 常见问题解决方案
问题:contains 大小写敏感
// 解决方案:统一转换为小写 if (text.tolowercase().contains(sub.tolowercase())) { ... }
问题:substring 索引计算错误
// 正确计算结束索引 int endindex = startindex + substring.length();
问题:处理多字节字符(中文)
string chinese = "你好世界"; // substring 正确处理多字节字符 system.out.println(chinese.substring(0, 2)); // "你好"
3. 性能优化技巧
// 当需要多次检查包含关系时 int index = text.indexof(sub); if (index != -1) { // 直接使用index,避免二次查找 string before = text.substring(0, index); // ... }
六、完整示例代码
public class stringoperations { public static void main(string[] args) { string text = "java编程很有趣,java是最好的编程语言之一"; string sub = "java"; string context = getsubstringcontext(text, sub); system.out.println(context); } public static string getsubstringcontext(string text, string sub) { if (text == null || sub == null) { return "输入不能为null"; } if (!text.contains(sub)) { return "未找到子串: \"" + sub + "\""; } int start = text.indexof(sub); int end = start + sub.length(); string before = (start > 0) ? text.substring(0, start) : "[开头]"; string after = (end < text.length()) ? text.substring(end) : "[结尾]"; return string.format("前文: \"%s\", 子串: \"%s\", 后文: \"%s\"", before, sub, after); } }
输出结果:
前文: "", 子串: "java", 后文: "编程很有趣,java是最好的编程语言之一"
总结
- contains 方法:
- 用于检查字符串是否包含子串
- 底层基于 indexof 实现
- 大小写敏感,需注意匹配规则
- substring 方法:
- 用于截取字符串的指定部分
- 有两种重载形式
- 必须正确处理索引边界
- 结合使用:
- 先用 contains 检查存在性
- 再用 indexof 获取位置
- 最后用 substring 提取前后文
- 注意处理边界情况(开头、结尾)
- 最佳实践:
- 添加空值检查
- 明确区分前后文
- 使用格式化输出提高可读性
- 考虑多字节字符支持
通过深入理解 contains 和 substring 方法的工作原理及结合使用技巧,您可以更有效地处理字符串操作任务,编写出健壮、高效的代码。
到此这篇关于java 字符串操作之contains 和 substring 方法最佳实践与常见问题的文章就介绍到这了,更多相关java contains 和 substring使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论