嘿傢伙,我已經提出,應該找到主串子串的功能,但它不能正常工作,這裏是代碼:C++查找字符串代碼,邏輯錯誤
char *mystrstr (char *s1, char *s2)
{
int i=0, j=0, k=0,t=0, l;
char* s3 = NULL;
char* s4 = NULL;
l = mystrlen (s2);
k = mystrlen(s1);
//s1 is the main string and s2 is the substring
if (*(s1 + i) == '\0') //checks if the main string is not null.
return s1;
while (*(s1 + i) != '\0' && *(s2 + i) != '\0')// if both the strings are not null then the program proceeds
{
while (s1[i] != s2[0] && s1 != NULL)//loop runs till the first letter of substring is found in the main string.
{
i++;
}
if (*(s1 + i) == '\0')
return NULL;
t = i;//stores the position where the first substrign was found
while (s1[i] == s2[j] && s1[i] != '\0' && s2[j] != '\0')
{
i++;//takes tho the nextl letter of the main string
j++;//to the next letter of the substring.
}
}
if (l == j)//if all letters of the substring is found in the main string only then this condition will be true.
{
s3 = &s1[t];
}
return s3;
}
能任何人都會說出什麼不對,或者至少給我一個提示?
所以根據給出的建議我改變了我的代碼,它給了我想要的結果。這是新代碼 -
的char * mystrstr(字符* S1,字符* S2) {
int i = 0, j = 0, k = 0, t = 0, l;
char* s3 = NULL;
char* s4 = NULL;
l = strlen(s2);
k = strlen(s1);
if (*(s1 + i) == '\0' && *(s2 + i) != '\0')
return NULL;
if (*(s1 + i) != '\0' && *(s2 + i) == '\0')
return s1;
if (*(s1 + i) == '\0')
return s1;
while (*(s1 + i) != '\0')
{
while (s1[i] != s2[j] && s1 != NULL)
{
i++;
j = 0;
}
if (*(s1 + i) == '\0')return NULL;
t = i;
while (s1[i] == s2[j] && s1[i] != '\0'&&s2[j] != '\0')
{
i++;
j++;
}
if (l == j){
s3 = &s1[t];
return s3;
}
}
return NULL;
}
反正有做使代碼更高效。我使用此代碼來查找主字符串形式的子字符串。
對於英語不好的人感到抱歉 – user3458561
用調試程序遍歷代碼。 –
爲什麼不使用'std :: string'類中的'substr'? – Caduchon