返回子字串的位置

來源:互聯網
上載者:User

今天在論壇上看了個發問的文章,是問他的那個程式編譯出錯是咋回事,我拷了下他的程式,發現是一些看不見的字元有問題(其他人的回答是程式裡有全形空白字元),刪除之後就OK了。

後來仔細再看他的程式,發現有點問題,他的那個函數原型是int func(char *str, char *substr);目的看str中是否有子字串substr,如果有則返回第一次出現的位置,如果沒有則返回-1。但我使用幾組資料測試了下,發現如果substr第一個字元不在str裡則返回-1,否則返回這個字元在str裡的位置。我根據他的思路修改了一下,能夠正確返回子字串的位置,但由於只測試了幾組資料,所以可能會有bug,先記下,後面有時間再仔細看看。
樓主:

#include <iostream>using namespace std;int func(char *str, char *substr){    char *cur = substr;    while(*str != '\0')    {        int count = 0;        if(*str == *cur)        {            while(*cur != '\0')            {                if(*cur++ == *str++)                ;                else                    break;            }            if(*cur == '\0')            return count + 1;            cur = substr;        }        else        {            str++;            count++;        }    }    return -1;}int main(){    char *str = "abcde";    char *substr = "cd";    cout << func(str, substr) << endl;    system("pause");    return 0;}

後來修改版:

#include <iostream>using namespace std;int func(char *str, char *substr){int count = -1;int temp = 0;char* cur = str;if(strlen(str) < strlen(substr)){return count;}else{bool flag = false;while(*cur != '\0'){for(unsigned int i=0; i<strlen(substr); ++i) {if(*(cur+i) == *(substr+i)){flag = true;}else{flag = false;break;}}if(flag == true){count = temp;break;}temp++;cur++;}}return count;}int main(){char *str = "abcde";char *substr = "";cout << func(str, substr) << endl;system("pause");return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.