Reputation: 29
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
.
Upvotes: 1
Views: 4921
Reputation: 134356
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,
<
[tag opening angle bracket] using strchr()
>
[tag closing angle bracket] using strchr()
.tag
value.<
[tag opening angle bracket] using strrchr()
>
[tag closing angle bracket] using strrchr()
.tag
value, if equals, do a memcpy()
/ strdup()
from acualarray[first_last_index]
(closing starting tag) upto acualarray[last_first_index]
(starting of closing tag.)Upvotes: 0
Reputation: 214300
strstr()
.[ [start of sub string 1] + [length of sub string 1] ]
and [start of sub string 2]
is the string you are interested in.strncpy()
or memcpy()
.Upvotes: 4
Reputation: 53016
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;
}
Upvotes: 1