【问题标题】:Extract string between two specific strings in C在C中的两个特定字符串之间提取字符串
【发布时间】:2015-05-18 11:42:20
【问题描述】:

如何提取两个指定字符串之间的字符串? 例如: <title>Extract this</title>。有没有使用strtok() 或更简单的方法来获取它?

编辑:指定的两个字符串是<title></title>,提取的字符串是Extract this

【问题讨论】:

  • strstr() 更好。
  • 只是为了呼应@iharob 先生所说的话,请参阅here
  • 我认为 OP 想要类似于 <title>[extract me]<title> 的东西作为 regexp
  • sscanf(string, "<title>%[^<]</title>", extracted_string);sscanf(string, "%*[^>]>%[^<]<%*[^>]>" , extracted_string); 将完成这项工作。还建议检查返回值。第一个 sscanf 中的 </title> 和第二个中的 <%*[^>]> 不是必需的。

标签: c string strtok


【解决方案1】:
  • 使用strstr() 搜索第一个子字符串。
  • 如果找到,保存子字符串的数组索引
  • 从那里,搜索下一个子字符串。
  • 如果找到,[ [start of sub string 1] + [length of sub string 1] ][start of sub string 2] 之间的所有内容都是您感兴趣的字符串。
  • 使用strncpy()memcpy() 提取字符串。

【讨论】:

  • @SouravGhosh 子字符串 1:<title>,子字符串 2 </title>。有什么问题?
  • 没什么。傻我。 :-)
【解决方案2】:

这是一个示例,它不检查输入字符串的完整性

#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;
}

【讨论】:

  • 如果value被声明在栈上,你必须释放它吗?
  • @user1717828 不,你不能释放它。
  • @user1717828 它不是堆栈变量,请仔细阅读代码。指针存储在堆栈上,指针指向的数据显然在堆上,因为它是在extract() 中使用malloc() 分配的。
  • 哎呀,还在学习C!所以你将result指向堆上的内存,返回result指向value的指针,最后运行free(value);来释放result指向的内存?使用与分配初始分配不同的指针来释放空间是标准的吗?很抱歉编辑错误。
  • 是指向malloc()返回的同一个地址的不同指针。
【解决方案3】:

The answer@Lundin 先生写的不错。但是,只是为了添加一些更通用的方法,(不依赖于 &lt;tag&gt; 值本身),您也可以这样做,

  1. 使用strchr() 定位&lt; [标签左尖括号] 的第一个实例
  2. 使用strchr() 查找&gt; [标签右尖括号] 的第一个实例。
  3. 保存索引和两个索引的差异,将字符串复制到临时数组中。将被视为tag 值。
  4. 使用strrchr() 定位&lt; [标签左尖括号] 的最后一个实例
  5. 使用strrchr() 查找&gt; [标签右尖括号] 的最后一个实例。
  6. 再次,保存索引和两个索引的差异,将字符串复制到另一个临时数组。与之前存储的tag 值进行比较,如果相等,则从acualarray[first_last_index](结束开始标签)到acualarray[last_first_index](结束标签开始)执行memcpy() / strdup()

【讨论】:

    猜你喜欢
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多