Searching strings C
Posted
by
Skittles
on Stack Overflow
See other posts from Stack Overflow
or by Skittles
Published on 2012-10-13T03:34:23Z
Indexed on
2012/10/13
3:36 UTC
Read the original article
Hit count: 106
First time posting here so I'm sorry if I mess up. I need to search a string and return any strings containing the search data with the search data highlighted. If my string is Hi my name is and I searched name it would produce Hi my NAME is
This is a quick code I wrote that works but it only works once. If I try and search again it seg faults.
I was hoping someone could hint me at a better way to write this because this code is disgusting!
void search(char * srcStr, int n){
int cnt = 0, pnt,i = 0;
char tmpText[500];
char tmpName[500];
char *ptr, *ptr2, *ptrLast;
int num;
while(*(node->text+cnt) != '\0'){ //finds length of string
cnt++;
}
for(pnt = 0; pnt < cnt; pnt++){ //copies node->text into a tmp string
tmpText[pnt] = *(node->text+pnt);
}
tmpText[pnt+1] = '\0';
//prints up to first occurrence of srcStr
ptr = strcasestr(tmpText, srcStr);
for(num = 0; num < ptr-tmpText; num++){
printf("%c",tmpText[num]);
}
//prints first occurrence of srcStr in capitals
for(num = 0; num < n; num++){
printf("%c",toupper(tmpText[ptr-tmpText+num]));
}
ptr2 = strcasestr((ptr+n),srcStr);
for(num = (ptr-tmpText+n); num < (ptr2-tmpText); num++){
printf("%c",tmpText[num]);
}
while((ptr = strcasestr((ptr+n), srcStr)) != NULL){
ptr2 = strcasestr((ptr+n),srcStr);
for(num = (ptr-tmpText+n); num < (ptr2-tmpText); num++){
printf("%c",tmpText[num]);
}
for(num = 0; num < n; num++){
printf("%c",toupper(tmpText[ptr-tmpText+num]));
}
ptrLast = ptr;
}
//prints remaining string after last occurrence
for(num = (ptrLast-tmpText+n); num < cnt; num++){
printf("%c",tmpText[num]);
}
}
© Stack Overflow or respective owner