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