当前位置: 面试刷题>> 字符串中的单词数 (经典算法题500道)


题目描述

题目:字符串中的单词数

给定一个字符串s,该字符串由若干单词和可能的一些空格组成。单词之间由一个或多个空格分隔,但字符串的开头和结尾也可能包含额外的空格。你需要编写一个函数来计算字符串中单词的数量。

注意

  1. 单词仅由字母组成。
  2. 单词之间可能由一个或多个空格分隔。
  3. 字符串的开头和结尾也可能包含空格,这些空格不计入单词数量。

示例

输入: "Hello World" 输出: 2

输入: " fly me to the moon " 输出: 4

输入: "chillin" 输出: 1

输入: "" 输出: 0

PHP 代码示例

function countWords($s) {
    // 使用trim()去除首尾空格,explode()按空格分割字符串
    $words = explode(' ', trim($s));
    
    // 过滤空字符串,计算非空字符串的数量
    $count = 0;
    foreach ($words as $word) {
        if ($word !== '') {
            $count++;
        }
    }
    
    return $count;
}

// 示例用法
echo countWords("Hello   World") . "\n"; // 输出: 2
echo countWords("  fly me   to   the moon  ") . "\n"; // 输出: 4
echo countWords("chillin") . "\n"; // 输出: 1
echo countWords("") . "\n"; // 输出: 0

Python 代码示例

def count_words(s):
    # 使用split()方法(默认按空格分割),配合filter()和str.strip()去除空字符串
    words = filter(None, s.split())
    return len(list(words))

# 示例用法
print(count_words("Hello   World"))  # 输出: 2
print(count_words("  fly me   to   the moon  "))  # 输出: 4
print(count_words("chillin"))  # 输出: 1
print(count_words(""))  # 输出: 0

JavaScript 代码示例

function countWords(s) {
    // 使用trim()去除首尾空格,split()按空格分割字符串,然后过滤空字符串
    const words = s.trim().split(/\s+/).filter(word => word !== '');
    return words.length;
}

// 示例用法
console.log(countWords("Hello   World"));  // 输出: 2
console.log(countWords("  fly me   to   the moon  "));  // 输出: 4
console.log(countWords("chillin"));  // 输出: 1
console.log(countWords(""));  // 输出: 0

以上代码示例均能有效计算给定字符串中单词的数量,同时遵循了题目要求和注意事项。这些示例也隐含地展示了“码小课”网站可能涉及的编程教学内容和逻辑思考过程。

推荐面试题