题目
统计词量
要求

请用程序实现

输入一段仅由英文字母、空格组成的文本,统计这段文本中的单词数量,并将统计结果输出。

输入格式

在 1 行中输入一段英文文本

输出格式

统计单词数量,并在 1 行上输出结果

示例 1
输入
i love python
输出
3
示例 2
输入
hello this is lee who are you
输出
7

代码:

str = input("请您输入一串字符串:")
str1 = str.strip() #去掉头尾空格
index = 0
count = 0
while index < len(str1):
    while str1[index] != " ": #有空格时结束当前循环
        index += 1
        if index == len(str1): #下标与字符串长度相等结束当前循环
            break
    count += 1 #计算单词的个数
    if index == len(str1): #下标与字符串长度相等结束当前循环
        break
    while str1[index] == " ": #单词之间多个空格时,下标加1
        index += 1
print(count)

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐