思路是通过循环遍历s的所有字符来统计数字字符的个数。以下分别是C和C++的程序。注意ctype.h/cctype头文件里声明的isdigit函数可以直接判断一个字符是不是数字字符。
C版本:
#include
size_t fun(const char *s)
{
size_t count = 0;
for (size_t i = 0; s[i] != 0; ++i) if (isdigit(s[i])) ++count;
return count;
}
C++版本:
#include
std::string::size_type fun(std::string &s)
{
std::string::size_type count = 0;
for (char c : s) if (isdigit(c)) ++count;
return count;
}
按你的描述统计数字字符个数应该是:
unsigned int fun(const char *s)
{
unsigned int digitNum = 0;
while (*s != '\0')
if (isdigit(*s++))
++digitNum;
return digitNum;
}
但是按你的例子,应该是统计连续数字的个数,那就该是:
static unsigned int fun(const char *s)
{
int flag = 0;
unsigned int digitNum = 0;
while (*s != '\0')
if (isdigit(*s++))
flag = 1;
else if (flag)
{
++digitNum;
flag = 0;
}
if (flag == 1)
++digitNum;
return digitNum;
}
#include
main()
{
int fun(char *s);
char *s="2def35adh25 3";
printf("%d\n",fun(s));
getch();
}
int fun(char *s)
{
int n=0;
for(;*s!='\0';s++)
{
if(*s>=48&&*s<=57)
n++;
}
return n;
}
#include
int fun(char *b)
{int i,j=0;
for(i=0;b[i]!='\0;i++)
if(b[i]>='0'&&b[i]<='9')
j++;
return j;
}
main()
{ char *s="2def35adh25 3";
int fun(char s);
printf("%d\n",fun(s));
getch();
}