Extract data between two delimiters

為{幸葍}努か 提交于 2019-12-06 10:36:39

I'd go with strstr().

For example:

#include <stdio.h>
#include <string.h>

int main(void) {
    char data[] = "<message%20type%3D\"info\"%20code"
                  "%3D\"20005\">%20<text>Conference%"
                  "20successfully%20modified</text>%"
                  "20<data>0117246</data>%20%20</mes"
                  "sage>%20";
    char *p1, *p2;
    p1 = strstr(data, "<text>");
    if (p1) {
        p2 = strstr(p1, "</text>");
        if (p2) printf("%.*s\n", p2 - p1 - 6, p1 + 6);
    }
    return 0;
}

There are functions strtok() and strtok_r() which can be used to extract the data based on the delimiters.

char a[100] = "%20Conference%20successfully%20modified%200117246%20%20%20";
char *p = strtok(a,"%");
while(p != NULL)
{
  // Save the value in pointer p
  p = strtok(NULL,"%");
}

If you want the string a to be unmodified then have a separate array b char b[100] and copy the string to b

strcpy(b,a);

Code and output:

#include <stdio.h>

int main(void) {
    char a[100] = "%20Conference%20successfully%20modified%200117246%20%20%20";
    char *p = strtok(a,"%");
    char n[20];
    while(p != NULL)
    {
      strcpy(n,p);
      p = strtok(NULL,"%");
      printf("%s\n",n);
    }
    return 0;
}

Output:

20Conference
20successfully
20modified
200117246
20
20
20

PS: strtok() modifies the passed string.Check man http://linux.die.net/man/3/strtok_r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!