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. }

<script type="text/javascript"> </script> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值