C++中统计给定字符串中的单词数
给定一个包含单词的句子或字符串,单词之间可能包含空格、换行符和制表符。任务是计算字符串中单词的总数并打印结果。
输入 − 字符串 str = “welcome to\n tutorials point\t”
输出 − 字符串中单词的数量为 − 4
说明 − 字符串中有四个单词,即 welcome、to、tutorials、point,其余是单词之间的空格(“ ”)、换行符(\n)和制表符(\t)。
输入 − 字符串 str = “\nhonesty\t is the best policy”
输出 − 字符串中单词的数量为 − 5
说明 − 字符串中有五个单词,即 honesty、is、the、best、policy,其余是单词之间的空格(“ ”)、换行符(\n)和制表符(\t)。
下面程序中使用的方法如下
这个问题有多种解法。所以让我们首先看看我们在下面的代码中使用的更简单的方案:
创建一个字符类型的数组来存储字符串,例如,str[]
声明两个临时变量,一个count用于计数字符串中单词的数量,另一个temp用于执行标志操作。
开始循环,当str不为空时
在循环内,检查IF *str = 空格 OR *str = 换行符 OR *str = 制表符,则将temp设置为0
否则,如果temp = 0,则将temp设置为1并将count的值加1
将str指针加1
返回count中的值
打印结果
示例
#include
using namespace std;
//count words in a given string
int total_words(char *str){
int count = 0;
int temp = 0;
while (*str){
if (*str == ' ' || *str == '\n' || *str == '\t'){
temp = 0;
}
else if(temp == 0){
temp = 1;
count++;
}
++str;
}
return count;
}
int main(){
char str[] = "welcome to\n tutorials point\t";
cout<<"Count of words in a string are: "<<total_words(str);
return 0;
}输出
如果运行上述代码,将生成以下输出:
Count of words in a string are: 4
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP