英文字符串单词个数统计
时间: 2023-09-13 08:07:38 浏览: 114
可以使用以下Python代码实现英文字符串单词个数统计:
```python
string = "Hello, world! This is a test string."
# 使用split()方法分割字符串
words = string.split()
# 统计单词个数
count = len(words)
print("单词个数: ", count)
```
输出结果为:
```
单词个数: 8
```
上述代码中,使用`split()`方法将字符串按照空格分割成单词,并将其存储在一个列表中。然后使用`len()`函数统计列表中单词的个数。
相关问题
java用可变字符串统计英文字符串中单词个数
可以使用Java的可变字符串类StringBuilder来实现统计英文字符串中单词个数的功能。具体的实现过程如下:
1. 定义一个StringBuilder对象,用于存储英文字符串。
2. 遍历英文字符串中的每一个字符,判断是否为字母或数字。
3. 如果当前字符是字母或数字,则将其添加到StringBuilder对象中;
4. 如果当前字符不是字母或数字(如空格、逗号、句号等),则判断StringBuilder对象中是否有字符,如果有则表示一个单词结束,计数器加1,并清空StringBuilder对象。
5. 遍历完整个字符串之后,还需要再判断一次StringBuilder对象中是否有未统计的单词,如果有则将统计器加1。
下面是一个完整的示例代码:
```java
public static int countWords(String str) {
// 创建可变字符串对象
StringBuilder sb = new StringBuilder();
// 定义计数器
int count = 0;
// 遍历字符串
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
// 判断是否为字母或数字
if (Character.isLetterOrDigit(c)) {
sb.append(c);
} else {
// 如果字符串非空则表示遇到了单词分隔符
if (sb.length() > 0) {
count++;
sb.delete(0, sb.length());
}
}
}
// 再次判断是否有未统计的单词
if (sb.length() > 0) {
count++;
}
return count;
}
```
可以通过以下方式调用该方法:
```java
int count = countWords("hello world, this is a test.");
System.out.println("单词个数为:" + count); // 输出:单词个数为:7
```
c语言 统计一个字符串中的英文单词个数
以下是C语言统计一个字符串中的英文单词个数的代码示例:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, word_count = 0;
printf("请输入一个字符串:");
fgets(str, 100, stdin);
for (i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) { // 如果当前字符是字母
while (isalpha(str[i])) { // 继续往后找字母
i++;
}
word_count++; // 找到一个单词
}
}
printf("该字符串中的英文单词个数为:%d\n", word_count);
return 0;
}
```
该程序首先提示用户输入一个字符串,然后使用`fgets()`函数读取用户输入的字符串。接着,程序遍历整个字符串,如果当前字符是字母,则继续往后找字母,直到找到一个非字母字符,此时就找到了一个单词,单词计数器加1。最后,程序输出该字符串中的英文单词个数。