首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

字符串中求数目字个数

2012-11-11 
字符串中求数字个数题目要求对于给定的一个字符串,统计其中数字字符出现的次数。输入数据有多行,第一行是一

字符串中求数字个数
题目要求

对于给定的一个字符串,统计其中数字字符出现的次数。
 
输入数据有多行,第一行是一个整数a,表示测试实例的个数,后面跟着a行,每行包括一个由字母和数字组成的字符串。
 
对于每个测试实例,输出该串中数值的个数,每个输出占一行


以下是我的代码,输出以后是每行字符串中的字符总个数,而不是每行字符串中数字的个数,这是为什么,急求,谢谢!

#include<iostream>
#include<string>
#include<vector>
#include<cctype>
using namespace std;
int main()
{  
  vector<string> str;
string s;
int a;
cin>>a;
for(int i=0;i<a;++i)
{
cin>>s;
str.push_back(s);
}
  string::size_type jx;
for(vector<string>::size_type ix = 0; ix != str.size(); ++ix)
{
for(jx=0;jx!=str[ix].size();++jx)  
{
if(isdigit(str[ix][jx]))
++jx;
}
  cout<<jx<<endl;
}
return 0;
}
 比如输入
4
dasd23
asdasd342sad
sd45sad3
输出
6
12
4
而不是我想要的
2
3
3



[解决办法]
你把jx的当作索引,又把它当作计数器,所以错了。在我这死循环呢,没输出第3行的4。
再定义一个变量吧。

C/C++ code
#include<iostream>#include<string>#include<vector>#include<cctype>using namespace std;int main(){      vector<string> str;    string s;    int a;    cin>>a;    for(int i=0;i<a;++i)    {        cin>>s;        str.push_back(s);    }    string::size_type jx;    for(vector<string>::size_type ix = 0; ix != str.size(); ++ix)    {        string::size_type count = 0;        for(jx=0;jx!=str[ix].size();++jx)          {            if(isdigit(str[ix][jx]))                ++count;        }        cout<<count<<endl;    }    return 0;} 

热点排行