简体   繁体   English

在带有指针的数组中查找字符串

[英]find a string in an array with pointers

I have a problem, I need to test if a string is present in an other array in C using pointer. 我有一个问题,我需要使用指针测试字符串是否存在于C中的其他数组中。 I tried this, but it doesn't work, if anyone has any suggestion... here is the code I tried, thank you in advance... 我尝试了这个,但是没有用,如果有人有任何建议...这是我尝试过的代码,在此先感谢您...

/* Like the strstr() function. It returns a pointer to the first occurrence of the string aiguille in the string meule_de_foin.
 * @param meule_de_foin the string to search in
 * @param aiguille the string to find
 * @return a pointer to the first occurrence of the string aiguille in the string meule_de_foin if aiguille is in meule_de_foin, NULL otherwise
 */

const char * IMPLEMENT(indexOfString)(const char *meule_de_foin, const char *aiguille) {
    int isFound; isFound=0;
    int first; first=meule_de_foin;

    while(isFound==0){
        if(*aiguille=='\0' && *meule_de_foin=='\0'){
            isFound=1;
        } else if (*aiguille == *meule_de_foin){
            aiguille=aiguille+1;
            meule_de_foin=meule_de_foin+1;
        }else{
            isFound=2;
        }
    }

    if(isFound==1){
        return (first);
    }else{
        return(NULL);
    }
}

if(isFound==1){
    return (first);
}else{
    return(NULL);
}

You're only testing if two strings are completely equal. 您仅测试两个字符串是否完全相等。

You need to stop checking when you reach the end of the search string, even if you're not at the end of the string to search. 即使您不在搜索字符串的末尾,也需要停止检查,直到到达搜索字符串的末尾。

And if it's not found, you need to check again starting at the next character, and keep repeating this until you reach the end of the string. 而且,如果找不到该字符串,则需要从下一个字符开始再次检查,并不断重复此操作,直到到达字符串的末尾。 So you need another loop around the loop that searches. 因此,您需要围绕搜索循环的另一个循环。

int isFound = 0;
const char *first;
for (first = meule_de_foin; *first != '\0' && isFound != 1; first++) {
    isFound = 0;
    const char *search = aiguille;
    const char *cur = first;
    while (!isFound) {
        if (*search == '\0') { // End of search string
            isFound = 1;
        } else if (*search != *cur) { // Non-matching character, stop matching
            isFound = 2;
        } else { // Keep matching
            search++;
            cur++;
        }
    }
}

if (isFound == 1) {
    return first;
else {
    return NULL;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM