编写程序,统计输入字符串中单词的个数,并输出统计结果
时间: 2024-02-26 13:57:41 浏览: 65
好的,以下是 Python 语言的代码实现:
```python
string = input("请输入一个字符串:")
count = 0
for i in range(len(string)):
if string[i] == ' ':
if i > 0 and string[i-1] != ' ':
count += 1
if string[-1] != ' ':
count += 1
print("该字符串中单词的个数为:", count)
```
运行结果如下:
```
请输入一个字符串:Hello World! This is a test.
该字符串中单词的个数为: 6
```
解释一下代码:
- 首先通过 `input()` 函数获取用户输入的字符串。
- 然后定义一个变量 `count` 用于计数,初值为 0。
- 通过 `for` 循环遍历字符串中的每个字符。
- 如果遇到空格,则检查它前面的字符是否也是空格,如果不是则将计数器加 1。
- 最后需要检查字符串末尾是否还有单词,如果有则将计数器再加 1。
- 最后输出计数器的值即可。
相关问题
编写程序,统计字符串中单词的个数
以下是一个统计字符串中单词个数的Python程序示例:
```python
def count_words(string):
words = string.split() # 将字符串按空格分割成单词列表
return len(words) # 返回单词列表的长度
s = input("请输入一个字符串:")
word_count = count_words(s)
print("字符串中单词的个数:%d" % word_count)
```
该程序首先定义了一个名为`count_words`的函数,该函数接受一个字符串作为参数。在函数内部,使用`split()`方法将字符串按空格分割成单词列表,并使用`len()`函数获取单词列表的长度,即单词的个数。最后,将统计结果打印出来。
编写程序,统计字符串中英文单词的个数
下面是一个简单的Python程序,可以统计字符串中英文单词的个数:
```python
import re
def count_words(text):
# 使用正则表达式匹配单词
words = re.findall(r'\b\w+\b', text)
# 统计英文单词个数
count = sum(1 for word in words if word.isalpha())
return count
# 测试程序
text = "Hello, world! This is a test string."
count = count_words(text)
print("There are", count, "English words in the text.")
```
程序中使用了正则表达式来匹配单词,然后使用isalpha()函数判断单词是否为英文单词,最后统计英文单词的个数。运行程序,输出如下:
```
There are 7 English words in the text.
```
需要注意的是,该程序只能统计纯英文单词,如果字符串中包含数字或符号,则不会被统计为单词。