找到字符串中最长的单词,并返回它的长度
function findLongestWordLength(str) {
// 如果字符串为空,返回0
if (!str) {
return 0;
}
// 将字符串按空格分割成单词数组
const words = str.split(' ');
// 使用reduce方法遍历单词数组,找到最长的单词长度
const longestLength = words.reduce((maxLength, currentWord) => {
// 去除单词两端的空格和标点符号,只保留字母、数字和下划线
const cleanedWord = currentWord.replace(/[^a-zA-Z0-9_]/g, "");
return Math.max(maxLength, cleanedWord.length);
}, 0);
return longestLength;
}
// 测试用例
console.log(findLongestWordLength("The quick brown fox jumped over the lazy fox")); // 输出 6 (jumped)
console.log(findLongestWordLength("This is a string with some words!")); // 输出 6 (string)
console.log(findLongestWordLength("Hello, world.")); // 输出 5 (Hello) or 5 (world) depending on implementation without cleaning. With cleaning, it's 5 for both.
console.log(findLongestWordLength("")); // 输出 0
console.log(findLongestWordLength(null)); // 输出 0
console.log(findLongestWordLength("one_two three")); // 输出 7 (one_two)
代码解释:
- 处理空字符串: 函数首先检查输入字符串是否为空或 null。如果是,则返回 0。
- 分割字符串:
str.split(' ')
将字符串按空格分割成一个单词数组。 - 使用 reduce 查找最长长度:
reduce
方法遍历单词数组。它接受两个参数:maxLength
:累加器,存储到目前为止找到的最长单词的长度。currentWord
:当前正在处理的单词。
- 清理单词 (重要!): 正则表达式
replace(/[^a-zA-Z0-9_]/g, "")
用于去除单词开头或结尾的标点符号。这可以防止标点符号被计入单词长度。例如,"Hello," 会被清理成 "Hello"。 - 比较长度:
Math.max(maxLength, currentWord.length)
比较当前单词的长度和maxLength
,并将较大的值赋给maxLength
。 - 返回最长长度: 最后,
reduce
方法返回maxLength
,即最长单词的长度。
改进和替代方案:
- 使用
map
和Math.max
: 可以使用map
将每个单词的长度映射到一个数组,然后使用Math.max(...lengths)
找到最大值。这种方法更简洁,但可能在处理非常大的字符串时效率略低。
function findLongestWordLength(str) {
if (!str) return 0;
const lengths = str.split(' ').map(word => word.replace(/[^a-zA-Z0-9_]/g, "").length);
return Math.max(...lengths);
}
- 直接使用 for 循环: 对于简单的任务,for 循环可能更易于理解。
function findLongestWordLength(str) {
if (!str) return 0;
let maxLength = 0;
const words = str.split(' ');
for (let i = 0; i < words.length; i++) {
const cleanedWord = words[i].replace(/[^a-zA-Z0-9_]/g, "");
maxLength = Math.max(maxLength, cleanedWord.length);
}
return maxLength;
}
选择哪种方法取决于个人偏好和代码风格。reduce
方法通常被认为更函数式,而 for
循环更直接。 map
和 Math.max
的组合提供了简洁性。 选择适合你的方法即可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通