写一个函数 参数是字串和长度,返回值是这个文章中单词的个数

operatingtuzi 2008-11-21 11:13:53
函数的参数是字串和长度,返回值是这个文章中单词的个数。
单词之间以空格 回车 或者制表符分割
我是这么写的
int fun(char *a,int n)
{
int count=0;
for(int i=0;i<n;i++)
{
if(a[i]==' '||a[i]=='\n'||a[i]=='\t')
count++;
}
return ++count;
}
这么写正确吗
如果第一个字符就是空格呢“ a b”实际是两个单词 但是会返回3的
如果中间有几个空格呢“a b c”a和b之间有两个空格,按照我的程序 会count+2的
怎么写才完善呢
...全文
74 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
kingteng 2008-11-23
  • 打赏
  • 举报
回复
2楼正解,c++ primer就是这么写的
haggard_hunan 2008-11-22
  • 打赏
  • 举报
回复
如果第一个字符就是空格呢“ a b”实际是两个单词 但是会返回3的 //处理前去空格
如果中间有几个空格呢“a b c”a和b之间有两个空格,按照我的程序 会count+2的//这个多判断一下

用strbrk或stringstream处理此类情况会很方便!
operatingtuzi 2008-11-22
  • 打赏
  • 举报
回复
istringstream stream(str);
while(stream>>str2)
这个是什么意思?
还有这个?string str(s,s+n);
yangkunhenry 2008-11-21
  • 打赏
  • 举报
回复

#include "stdafx.h"
#include <sstream>
#include <iostream>
#include <string>
using namespace std;
int fun(string &str,size_t n)
{
int cnt=0;
string str2;
istringstream stream(str);
while(stream>>str2)
++cnt;
return cnt;
}
int _tmain(int argc, _TCHAR* argv[])
{
char *s="write a \tfun for \n you!";
size_t n=strlen(s);
string str(s,s+n);
int cnt=fun(str,n);
cout<<cnt<<endl;
return 0;
}

65,210

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧