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.
Example:
If my initial string is: Hi my name is, and my search term is: name, then the output should be: 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]);
}
}
Only because I’m stupid lazy and there were no pre-requisites for conformance with multi-byte characters (which makes this a helluva lot harder). There are more efficient ways, but barring a platform with
strupr()andstrlwr()it is hard to get much simpler.Note: this takes into account the possibility of the search txt being present in the source in mixed case rather than strictly lower case. If the problem domain is restricted to only substitute exact lower-case matches, the source dup can be dropped as well, thereby making this about a half-dozen fewer lines still.
Sample invoke looks like:
and output looks like this: