C/C++字串尋找

來源:互聯網
上載者:User
  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. }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.