C++计算单词个数

一个长度为N的字符串,求其中单词个数。

输入1:

hello liyang

输出1:

2

输入2:

we       are     heros

输出2: 

3

分析:

去掉其中多余的空格,并计算空格个数,即单词数为其个数+1

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int main(){
	string s;
	int n,m;
	getline(cin,s);
	n=s.length();
	for(int i=0;i<n-1;)       //除去多余空格 
	{
		if(s[i]==' ')
		{
		if(s[i+1]==' ')
		{
			s.erase(i+1,1);
		}
		else
		i=i+1;
		}
		else
		i=i+1;
	}
	n=0;
	m=s.length();
	for(int i=0;i<m;i++)    //计算空格数 
	{
		if(s[i]==' ')
		n=n+1;
	}
	cout<<n+1;
}

猜你喜欢

转载自blog.csdn.net/wallyIII/article/details/81144255