[Pointers and C-String]D. Liang 7.10 Occurrences of each digit in a string
Description:
Write a function that counts the occurrences of each digit in a string using the following header:
int * count(const char * const s);
The function counts how many times a digits appears in the string. The return value is an array of ten elements, each of which holds the count for a digit. For example, after executing int counts[] = count("12203AB3")
, counts[0]
is 1, counts[1]
is 1, counts[2]
is 2, counts[3]
is 2.
Hint:
Don’t submit the main() function.
Programme:
//Date:2020/5/18
//Author:Kamenrider Justice
int * count(const char * const s)
{
int i,length,*count;
count=(int*)malloc(10*sizeof(int));//分配内存
for(i=0;i<10;i++)//初始化为0
{
count[i]=0;
}
length=strlen(s);
for(i=0;i<length;i++)
{
switch(s[i])//采用switch语句
{
case '0':
{
count[0]++;
break;
}
case '1':
{
count[1]++;
break;
}
case '2':
{
count[2]++;
break;
}
case '3':
{
count[3]++;
break;
}
case '4':
{
count[4]++;
break;
}
case '5':
{
count[5]++;
break;
}
case '6':
{
count[6]++;
break;
}
case '7':
{
count[7]++;
break;
}
case '8':
{
count[8]++;
break;
}
case '9':
{
count[9]++;
break;
}
default:
{
break;
}
}
}
return count;
}
数据结构核心原理与算法应用