问题
I just want to know whether it is possible to pick up the data that is present between two delimiters (delimiter being a string).
For example the original string is as under
<message%20type%3D"info"%20code%3D"20005">%20<text>Conference%20successfully%20modified</text>%20<data>0117246</data>%20%20</message>%20
and I want the data that is present between <text>
tags. The string from which i need the data can be different. The string can also be like this
<message%20type%3D"info"%20code%3D"20001">%20<text>Conference%20deleted</text%20%20<vanity>0116976</vanity>%20</message>%20<message%20type%3D"info"%20code%3D"20002">%20<text>Number%20of%20conferences%20deleted</text>%20<data>1</data>%20%20</message>%20
but I always need the data present between the <text>
tags.
So is it possible in C language or is there any alternative?
回答1:
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;
}
回答2:
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
来源:https://stackoverflow.com/questions/28451377/extract-data-between-two-delimiters