C/C++字符串查找

  1. //编写函数int strstr(char srcstr[],char deststr[] )
  2. //在字符串srcstr中查找字符串deststr,如果找到,则返回字符串deststr在字符串srcstr中的位置。
  3. #include <stdio.h>
  4. #include <conio.h>
  5. #define MAX 256
  6. int strstr(char srcstr[],char deststr[]);
  7. int main()
  8. {
  9.     char srcstr[MAX];
  10.     char deststr[MAX];
  11.     char c;  
  12.     int n;
  13.     int index;
  14.     
  15.      
  16.     n=0;
  17.     printf("请输一个源字符串:/n");
  18.     while((c=getchar()) !='/n')
  19.     {
  20.            srcstr[n] =c;
  21.            n++;              
  22.     }    
  23.     
  24.     n=0;
  25.     printf("请输入一个你要查找的字符:/n");    
  26.     while((c=getchar()) !='/n')
  27.     {
  28.            deststr[n] =c;
  29.            n++;              
  30.     }    
  31.    
  32.     index = strstr(srcstr,deststr);
  33.     
  34.     if (index>=0)
  35.     {
  36.         printf("找到了,在源字符串中的位置是: %d/n", index);
  37.     }
  38.     else
  39.         printf("没有找到哦/n");
  40.         
  41.     getch();
  42.     return 0;
  43. }
  44. int strstr(char srcstr[],char deststr[] )
  45. {
  46.     int j=0;
  47.     for (int i=0;srcstr[i]!='/0';i++)
  48.     {
  49.         if (deststr[0]==srcstr[i])
  50.         {
  51.             while (deststr[j]!='/0'&&srcstr[i+j]!='/0')
  52.             {
  53.                 j++;
  54.                 if (deststr[j]!=srcstr[i+j])
  55.                 {
  56.                     break;
  57.                 }
  58.             }
  59.         }
  60.         if (deststr[j]=='/0')
  61.         {
  62.             return i;
  63.         }
  64.     }
  65.     return -1;
  66. }


你可能感兴趣的:(c)