20201003--统计数字字符个数(奥赛一本通 P98 1--字符类型和字符数组)

输入一行字符,统计出其中数字字符的个数

输入:一行字符串,总长度不超过255

输出:一行,输出字符串里面数字字符的个数。

样例输入:Peking University is set up at 1898

样例输出:4

 解法1(用char数据类型):

#include <bits/stdc++.h>

using namespace std;

char a[256];

int box;

int n,m;//分别代表像素点的行数和列数

int main()

{

  gets(a);

  int b=strlen(a);

 for (int i=0;i<=b;i++)

  { if(a[i]>='0' && a[i]<='9')

      {box++;}

  }

  cout<<box<<endl;

  return 0;
}

 解法2(用string数据类型):

#include <iostream>

#include <cstring>

#include <string>

#include <cmath>

using namespace std;

string a="";

int main()

{

  getline(cin,a);//getline用于获取string类型字符串

  int box=0;

  for(int i=0;i<=a.size();i++)

    {

      if(a[i]>='0' && a[i]<='9')

         {box++;}

    }

  cout<<box<<endl;

  return 0;

}

原文地址:https://www.cnblogs.com/whcsrj/p/13763633.html