Extract string between two specific strings in C

只谈情不闲聊 提交于 2019-12-02 10:34:59

问题


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() or memcpy().



回答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,

  1. Locate the first instance of < [tag opening angle bracket] using strchr()
  2. find the first first instance of > [tag closing angle bracket] using strchr().
  3. save the indexes and the difference of two indexes, copy the string to a temporary array. will treat as the tag value.
  4. Locate the last instance of < [tag opening angle bracket] using strrchr()
  5. find the last instance of > [tag closing angle bracket] using strrchr().
  6. Again, save the indexes and the difference of two indexes, copy the string to another temporary array. Compare with previously stored 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.)


来源:https://stackoverflow.com/questions/30302294/extract-string-between-two-specific-strings-in-c

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