Calculate the number of words in a sentence C language and Python implementation

Separate a space into a word, and count the total number of words in a sentence.

C language implementation

#include<stdio.h>
#include<string.h>

int main()
{
    
    
	char str[80]; 
	int word = 0, num = 0;
	// 1.获取输入的字符串
	printf("请输入一句话:\n");
	gets(str);
	// 2. 循环遍历字符串每个字符
	for(int i=0; str[i] != '\0'; i++)
	{
    
    
		// 3.其实 word=0, 表示前面是空格, 当出现一个字符,就会执行 else if 语句,表示得到一个单词
		//   此后word = 1, 知道再次循环到到 空字符,该单词结束,依次循环。 word 作为一个标志变量
		if(str[i] == ' ')
			word = 0;
		else if(word == 0)
		{
    
    
			word = 1;
			num ++;
		}
	}
	printf("%d\n", num);
	return 0;
}

Python implementation

  • It is easy to use functions. Of course, you can also imitate the steps in C and use python without the help of functions.
str1 = input("请输入一个句子:")
str1_list = str1.split()
print(len(str1_list))

Python implementation upgrade: determine the number of occurrences of each word

str1 = 'i am a luck dog , you are a luck dog ! my life is short, i use python, you ?'

dc = {
    
    }
# 首先还是以空格分出来 单词
l1 = str1.split()
# 列表元素去重
l2 = list(set(l1))
for i in l2:
    # 统计单词出现次数,并存入字典
    dc[i] = l1.count(i)
print(dc)
  • Generally speaking, there are many methods provided by python, and you must be familiar with these methods.
  • To solve problems in C language, first think about the steps and algorithm rules. Python solves the problem, as long as you come up with the overall idea, and then many detailed steps will be encapsulated, and you can find and use it directly.

Guess you like

Origin blog.csdn.net/pythonstrat/article/details/112787274