c ++计算字符串长度
Here you will get C++ program to count number of words in string.
在这里,您将获得C ++程序来计算字符串中的单词数。
First we initialize a counter variable to 1. Now iterate through string and count all the spaces, for each space increase the value of counter. Finally print the counter variable, it contains the number of words.
首先,我们将计数器变量初始化为1。现在遍历字符串并计算所有空格,为每个空格增加counter的值。 最后打印计数器变量,它包含单词数。
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
char a[100];
int i,count=1;
cout<<"Enter a string:";
gets(a);
for(i=0;a[i]!='\0';++i)
{
if(a[i]==' ')
count++;
}
cout<<"\nThere are "<<count<<" words in the given string";
return 0;
}
Output
输出量
Enter a string:how are you buddy?
输入一个字符串:你好吗?
There are 4 words in the given string
给定的字符串中有4个单词
翻译自: https://www.thecrazyprogrammer.com/2011/03/c-program-to-count-no-of-words-in-string.html
c ++计算字符串长度