
在编程实践中,我们经常需要处理文本数据。其中一个常见任务是从一个包含多个单词的句子中,根据指定的单词长度,筛选并返回所有符合条件的单词。例如,给定字符串“monday is a new day”和长度3,我们期望得到{"new", "day"}。
传统的实现方式可能涉及手动遍历字符串,判断字符是否为空格来识别单词边界,然后截取子字符串并检查其长度。这种方法通常代码量较大,逻辑复杂,且容易出错,尤其是在处理多个连续空格或字符串开头/结尾的空格时。
Java 8引入的Stream API为处理集合数据提供了强大而简洁的工具。结合String.split()方法,我们可以非常优雅地解决这个问题。
以下是实现上述逻辑的Java代码:
import java.util.Arrays;
import java.util.Objects; // 用于Objects.requireNonNullElseGet,处理null或空字符串
public class WordExtractor {
/**
* 从给定字符串中提取所有指定长度的单词。
*
* @param sentence 输入的句子字符串。
* @param wordLength 目标单词的长度。
* @return 包含所有符合长度要求的单词的字符串数组。
* 如果输入句子为空或null,则返回空数组。
*/
public String[] findWordsByLength(String sentence, int wordLength) {
// 1. 处理null或空字符串输入,避免NullPointerException
// Objects.requireNonNullElseGet(sentence, () -> "") ensures sentence is not null
// .trim() removes leading/trailing spaces
// .split("\s+") splits by one or more whitespace characters
String[] words = Objects.requireNonNullElseGet(sentence, () -> "")
.trim()
.split("\s+");
// 2. 将单词数组转换为流,并进行过滤和收集
return Arrays.stream(words)
.filter(word -> !word.isEmpty() && word.length() == wordLength) // 过滤空字符串和符合长度的单词
.toArray(String[]::new); // 将结果收集到新的字符串数组中
}
public static void main(String[] args) {
WordExtractor extractor = new WordExtractor();
// 示例1
String s1 = "Monday is a new day";
int n1 = 3; // 3字母单词
String[] result1 = extractor.findWordsByLength(s1, n1);
System.out.println("Input: "" + s1 + "", Length: " + n1 + " -> Result: " + Arrays.toString(result1)); // 预期: {"new", "day"}
// 示例2
String s2 = "Monday is a new day";
int n2 = 2; // 2字母单词
String[] result2 = extractor.findWordsByLength(s2, n2);
System.out.println("Input: "" + s2 + "", Length: " + n2 + " -> Result: " + Arrays.toString(result2)); // 预期: {"is"}
// 示例3:包含多个空格
String s3 = " hello world java ";
int n3 = 5;
String[] result3 = extractor.findWordsByLength(s3, n3);
System.out.println("Input: "" + s3 + "", Length: " + n3 + " -> Result: " + Arrays.toString(result3)); // 预期: {"hello", "world"}
// 示例4:空字符串或null输入
String s4 = "";
int n4 = 3;
String[] result4 = extractor.findWordsByLength(s4, n4);
System.out.println("Input: "" + s4 + "", Length: " + n4 + " -> Result: " + Arrays.toString(result4)); // 预期: {}
String s5 = null;
int n5 = 3;
String[] result5 = extractor.findWordsByLength(s5, n5);
System.out.println("Input: "" + s5 + "", Length: " + n5 + " -> Result: " + Arrays.toString(result5)); // 预期: {}
}
}通过结合String.split()方法和Java 8 Stream API,我们可以用非常简洁、高效且易于理解的方式,从字符串中提取指定长度的单词。这种现代Java编程风格不仅提升了代码质量,也降低了维护成本。掌握这种模式对于处理文本数据和利用Java函数式编程特性至关重要。
立即学习“Java免费学习笔记(深入)”;
以上就是Java:高效提取字符串中指定长度单词的方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号