1. 设置标志位实现
#include<iostream>
using namespace std;
int main()
{
int flag=0;
int count=0,i=0;
char str[1000]={0};
gets(str);
for (i=0;str[i]!='\0';i++)
{
if (str[i]==' ') //空格设置标志位
{
flag=0;
}
else if(flag==0) //非空格,但之前为空格
{
count++;
flag=1;
}
}
printf("%d\n",count);
system("pause");
return 0;
}
2.使用strtok函数
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i=0;
int count=0;
char str[1000]={0};
gets(str);
while(str[i]!='\0') //将非字母字符置成空格
{
if ((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z'))
{
i++;
}
else
{
str[i]=' ';
i++;
}
}
char *p=strtok(str," "); //进行字符串分割
while(p!=NULL) //统计
{
count++;
p=strtok(NULL," ");
}
printf("%d\n",count);
system("pause");
return 0;
}
统计一句话中每个单词出现的次数,考虑重复,但原单词出现顺序统计
#include <iostream>
#include <map>
#include <string>
using namespace std;
struct v_sCount //保存统计信息
{
int count; //单词出现次数
int v_ipos; //标识单词出现的顺序
};
int main()
{
int i=0;
int pos=1;
map<string,struct v_sCount> v_mCount;
map<string,struct v_sCount>::iterator v_pCount;
char *p=NULL;
char str[1000]={0};
gets(str);
while(str[i]!='\0') //出去单词中非字母字符
{
if ((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z'))
{
i++;
}
else
{
str[i]=' ';
i++;
}
}
p=strtok(str," "); //字符串分割函数(按空格) char * strtok(char *s, const char *delim);
while(p!=NULL) //统计出现次数
{
string tmp=p;
v_pCount=v_mCount.find(tmp);
if (v_pCount==v_mCount.end()) //第一次出现
{
struct v_sCount struct_tmp;
struct_tmp.count=1;
struct_tmp.v_ipos=pos++;
v_mCount.insert(pair<string,struct v_sCount>(tmp,struct_tmp));
}
else //已出现,更新值
{
v_pCount->second.count++;
}
p=strtok(NULL," "); //接着取字符串
}
//将统计结果输出
for(i=1;i<pos;i++)
{
for(v_pCount=v_mCount.begin();v_pCount!=v_mCount.end();v_pCount++)
{
if(v_pCount->second.v_ipos==i)
cout<<v_pCount->first<<' '<<v_pCount->second.count<<endl;
}
}
system("pause");
return 0;
}