问题
How do you extract strings between two specified strings?
For Example:
<title>Extract this</title>. Is there a simple way to get it using strtok() or anything simpler?
EDIT: The two specified strings are <title> and </title> and the string extracted is Extract this.
回答1:
- Search for the first sub string using
strstr(). - If found, save the array index of the sub string
- From there, search for the next sub string.
- If found, everything between
[ [start of sub string 1] + [length of sub string 1] ]and[start of sub string 2]is the string you are interested in. - Extract the string using
strncpy()ormemcpy().
回答2:
This is an example of how you can do it, it's not checking the input string integrity
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *extract(const char *const string, const char *const left, const char *const right)
{
char *head;
char *tail;
size_t length;
char *result;
if ((string == NULL) || (left == NULL) || (right == NULL))
return NULL;
length = strlen(left);
head = strstr(string, left);
if (head == NULL)
return NULL;
head += length;
tail = strstr(head, right);
if (tail == NULL)
return tail;
length = tail - head;
result = malloc(1 + length);
if (result == NULL)
return NULL;
result[length] = '\0';
memcpy(result, head, length);
return result;
}
int main(void)
{
char string[] = "<title>The Title</title>";
char *value;
value = extract(string, "<title>", "</title>");
if (value != NULL)
printf("%s\n", value);
free(value);
return 0;
}
回答3:
The answer by Mr. @Lundin is nice one. However, just to add a bit more generic approach, (without depending on the <tag> value itself), you can also do like,
- Locate the first instance of
<[tag opening angle bracket] using strchr() - find the first first instance of
>[tag closing angle bracket] using strchr(). - save the indexes and the difference of two indexes, copy the string to a temporary array. will treat as the
tagvalue. - Locate the last instance of
<[tag opening angle bracket] using strrchr() - find the last instance of
>[tag closing angle bracket] using strrchr(). - Again, save the indexes and the difference of two indexes, copy the string to another temporary array. Compare with previously stored
tagvalue, if equals, do amemcpy()/strdup()fromacualarray[first_last_index](closing starting tag) uptoacualarray[last_first_index](starting of closing tag.)
来源:https://stackoverflow.com/questions/30302294/extract-string-between-two-specific-strings-in-c