题目:
请编写一个函数,它在一个字符串中进行搜索,查找所有在一个给定字符集合中出现的字符。这个函数的原型应该如下:char *find_char( char const *source,char const *chars )
用到的知识:malloc动态分配,malloc()函数会在堆上动态分配一段连续的内存空间,大小为所需的总内存空间大小,并返回指向该内存空间的指针。用法:
char **result=malloc(max_count*sizeof(const char *));
sizeof(const char *)表示const char *占的字节数,再乘以max_count表示soucre中单词的数量,所需要的空间。为什么要用双重指针声明呢?char **result,便于给内存分配地址。
strchr():const char *q = strchr(chars, *p);这行代码将在 chars 指向的字符串中查找第一个匹配 *p 指向的字符的位置,并将指向该位置的指针赋值给 q。如果没有找到匹配的字符,q 将被赋值为 NULL。
代码如下:
#include<stdio.h>
#include<string.h>
const char **find_chars(const char *source,const *chars ,int*count)//声明一个指针函数
{
if(source==NULL||chars==NULL||*source=='\0'||*chars=='\0')
{
return NULL;
}
int max_count=strlen(source);//strlen计算source中字符数量;
const char **result=malloc(max_count *sizeof(const char *));/*开辟能够容纳source所以单词的空间,并赋予一个指针数组,便于分配管理;*/
*count=0;//count指针所指向的值赋值为0;
for(const char *p=source;*p!='\0';++p)//for循环遍历source中每个字符;
{
const char *q=strchr(chars,*p);/*将在 chars 指向的字符串中查找第一个匹配 *p 指向的字符的位置,并将指向该位置的指针赋值给 q。如果没有找到匹配的字符,q 将被赋值为 NULL。*/
if(q!=NULL)
{
result[*count]=p;//把第一个相同的字符的指针存储到result中的第一个位置;
(*count)++;
if(*count==max_count)//count指针位数等于source中最大字符数时;
{
break;
}
}
}
if(*count==0)//即是没有相同的字符,释放mollc空间并函数返回NULL;
{
free(result);
return NULL;
}
return result;
}
int main()
{
char source[]="abcdefg";
char str[20];
int i;
printf("请输入单词:\n");
gets(str);
int count;
const char **array=find_chars(source,str,&count);
if(array!=NULL)
{
printf("找到%d个相同的字符:",count);
for(i=0;i<count;++i)
{
printf("%c\t",*array[i]);
}
free(array);
}
else
{
printf("未找到\n");
}
return 0;
}
记录自己学习过程。