假設我們有一個字串,例如“((the))天氣通常很好((當))它的((春天))”我如何只決議“((”和“))”之間的單詞而不使用正則運算式.
uj5u.com熱心網友回復:
您可以使用strstr()defined in<string.h>來搜索"((",然后從那里搜索 for"))"以找到匹配的結尾:
#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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/518407.html
標籤:C解析c字符串
