C语言基础编程之指针实现字符位置查找

来源:互联网 发布:更新sql 编辑:程序博客网 时间:2024/06/05 21:16

  最近又再看C语言,看到练习里面有一个字符查找的题目,用指针实现的,试试做了一下。C里面指针是比较让人头疼的东西,那就从基础开始,慢慢让指针不再那么头疼。

 

  题目:编写一个函数,他在一个字符串中进行搜索,查找所有在一个给定字符集合中出现的字符,函数原型如下:

   char *find_char(char const *source, char const *chars);

 

  提示:查找source字符串中匹配chars字符串中任何字符的第1个字符,函数然后返回一个指向source中第1个匹配所找到的位置的指针。如果source中的有字符均不匹配chars中的任何字符,函数就返回一个NULL指针。如果任何一个参数为NULL,或任何一个参数所指向的字符串为空,函数也返回一个NULL指针。

 

比如:

  假定source指向ABCDEF。如果chars指向XYZJUR或者QQQQ,函数就返回一个NULL指针。如果chars指向XRCQEF,函数就返回一个指向sourceC字符的指针,参数所指向的字符串是绝不会被修改的。

 

注:

1.C函数库中有一个现成的函数strpbrk,它的功能就是完成本题的任务,所以不能使用;

2.不能使用任何用于操纵字符串的库函数,比如strcmpstrcpyindex等;

3.函数中的任何地方都不应该使用下标引用。

 

linux上用GCC编译测试过了,废话不说了,上代码:

 

#include <stdio.h>

#include <string.h>

 

char *find_char(char const *source, char const *chars)

{

       char srcch = '\0', subch = '\0';

       char *store_chars = chars;

       int flag = 0;

       if(*source == '\0')

       {

              return NULL;

              printf("The source string is null.\n");

       }

       while(*source != '\0')

       {    

              srcch = *source;

              while(*chars != '\0')

              {

                     subch = *chars;

                     if(srcch == subch)

                     {

                            flag = 1;

                            printf("Found the first character in the source string which match the char string!\n");

                            break;

                     }

                     chars++;

              }

              chars = store_chars;

              if(flag)

              {

                     return source;

              }

              source++;

       }

       return NULL;

       printf("Not found the matched character!\n");

}

 

main()

{

       char const *mother_str = "CRAZY GUY";

       char const *child_str = "SNOOZE";

       char *fir_ch = '\0';

       fir_ch = find_char(mother_str, child_str);

       if(fir_ch == NULL)

              printf("Thers is no matched character in the mother string.\n");

       else

              printf("The matched character is: %c\n", *fir_ch);

}