Reputation:
Say we have a string that goes like "((the)) weather is usually good ((when)) its ((spring))" How can I parse only the words between '((' and '))' without using regex.
Upvotes: 1
Views: 64
Reputation: 144951
You can use strstr()
defined in <string.h>
to search for "(("
, then search from there for "))"
to find the end of the match:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *get_word(const char *s, size_t *pos) {
const char *p1; // pointer to the next match
const char *p2; // pointer to the match end
p1 = strstr(s + *pos, "((");
if (p1 == NULL) {
*pos += strlen(s + *pos);
return NULL;
}
p1 += 2;
p2 = strstr(p1, "))");
if (p2 == NULL) {
// missing end string
*pos += strlen(s + *pos);
return NULL;
}
*pos = p2 + 2 - s;
return strndup(p1, p2 - p1); // allocate a copy of the match
}
int main() {
const char *str = "((the)) weather is usually good ((when)) it's ((spring))";
size_t pos = 0;
char *p;
while ((p = get_word(s, &pos)) != NULL) {
printf("%s\n", p);
free(p);
}
return 0;
}
Upvotes: 1