Reputation: 11
I have a problem, I need to test if a string is present in an other array in C using pointer. 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);
}
Upvotes: 0
Views: 541
Reputation: 781004
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;
}
Upvotes: 5