如何查找C风格字符串中逗号的个数

fanshaoer 2009-11-13 04:43:21

const char* p="ab12,32,123,9a"


我想做个判断,查找里面是否有三个逗号,有三个的话正常return.不是三个逗号的好,提示错误信息。

谢谢各位啦!!

...全文
445 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
fanshaoer 2009-11-16
  • 打赏
  • 举报
回复
count(strgrid.begin(),strgrid.end(),',');
prog_dong 2009-11-16
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 t1397018 的回复:]
楼上的2位哥,不是找位置,是找个数
从头到尾遍历一遍
int count = 0;
while( *p != '\0')
{
  if(*p++ = ''') //这里貌似应该是:if(',' == *p++)
    count++;
}
[/Quote]

^_^
fanshaoer 2009-11-16
  • 打赏
  • 举报
回复
string s = char* p;

然后再用标准库函数吧,虽然多了一步。。
evansun922 2009-11-16
  • 打赏
  • 举报
回复
....
fanshaoer 2009-11-16
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 t1397018 的回复:]
楼上的2位哥,不是找位置,是找个数
从头到尾遍历一遍
int count = 0;
while( *p != '\0')
{
  if(*p++ = ''')
    count++;
}
[/Quote]

谢谢。不是连续的逗号。。。。
fanshaoer 2009-11-16
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 goldgood 的回复:]
前端时间回答别人问题的时候正好写过,你该该就能用了C/C++ code
#include"string"
#include"iostream"using std::string;using std::cin;using std::cout;int main(int argc,char* argv[])
{string strInput="abc,def,ghi,jkl\ mnos,sadf,asgs\
f,sa,f,sa,fa,sdf";int nCount=0;//总个数int*nArray=newint[20];for(int i=0, j=0; i< strInput.length() ;++i)
{if(strInput[i]==',')
{
nCount++;
nArray[j++]= i;
}
}

cout<<"共有','"<<nCount<<"个\n";
cout<<"位置分别为字符串的";//序号0为第一位for(i=0; i< nCount;++i)
{
cout<<"第"<< nArray[i]<<"位";
}

delete[] nArray;return0;
}
[/Quote]

这个。。。。。我好像要改很多吧,你这是string,我是char*
cphj 2009-11-15
  • 打赏
  • 举报
回复
C++,用STL一句话就搞定了
int cnt = count(p, p+strlen(p), ',');
lovesi3344 2009-11-15
  • 打赏
  • 举报
回复
mark
学习了
Goldgood 2009-11-13
  • 打赏
  • 举报
回复
前端时间回答别人问题的时候正好写过,你该该就能用了

#include "string"
#include "iostream"

using std::string;
using std::cin;
using std::cout;

int main(int argc, char* argv[])
{
string strInput = "abc,def,ghi,jkl\
mnos,sadf,asgs\
f,sa,f,sa,fa,sdf";

int nCount = 0; //总个数
int *nArray = new int[20];

for(int i = 0, j = 0; i < strInput.length() ; ++i)
{
if(strInput[i] == ',')
{
nCount++;
nArray[j++] = i;
}
}

cout<< "共有','"<<nCount << "个\n";
cout<< "位置分别为字符串的";

//序号0为第一位
for(i = 0; i < nCount; ++i)
{
cout<< "第"<< nArray[i]<< "位 ";
}

delete[] nArray;
return 0;
}
t1397018 2009-11-13
  • 打赏
  • 举报
回复
楼上的2位哥,不是找位置,是找个数
从头到尾遍历一遍
int count = 0;
while( *p != '\0')
{
if(*p++ = ''')
count++;
}
AbnormalSubmarine 2009-11-13
  • 打赏
  • 举报
回复
调用库函数,或者自己挨个字符遍历
Caballeroo 2009-11-13
  • 打赏
  • 举报
回复
方法太多了:

逐个字符判断

或者strstr()

或者strchr()
magicpang 2009-11-13
  • 打赏
  • 举报
回复
strchr()
最适合了
Blue_may 2009-11-13
  • 打赏
  • 举报
回复
遍历查找计数。。。

64,637

社区成员

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

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