如何在C中的两个子串之间找到第n个子串?

时间:2018-04-10 02:41:49

标签: c string substring instance

我正在使用此函数在两个子字符串之间获取子字符串。

char * extract_between(const char *str, const char *p1, const char *p2/*, const int instance*/)
{
   //int count;
   const char *i1 = strstr(str, p1);
   /*for (count = 0; ; ++count) {
        const char *i1 = strstr(str, p1);
        if (count==instance)
            break;
   }*/
   if(i1 != NULL)
   {
      const size_t pl1 = strlen(p1);
      const char *i2 = strstr(i1 + pl1, p2);
      if(p2 != NULL)
      {
         /* Found both markers, extract text. */
         const size_t mlen = i2 - (i1 + pl1);
         char *ret = malloc(mlen + 1);
         if(ret != NULL)
         {
            memcpy(ret, i1 + pl1, mlen);
            ret[mlen] = '\0';
            return ret;
         }
      }
   }
   return 0;
}

我想修改它,以便它本身搜索子子字符串的第n个实例。这怎么可能?我尝试过(计数),但我不确定如何格式化。

1 个答案:

答案 0 :(得分:0)

这对你有用吗?

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char*
extract_between (const char* str, const char* p1, const char* p2, int instance)
{
  int count = -1;
  const char* i1 = str - 1;
  for (; count < instance; ++count) {
        i1 = strstr(i1 + 1, p1);
        if (i1 == NULL)
            return NULL;
  }
  const size_t pl1 = strlen(p1);
  const char* i2 = strstr(i1 + pl1, p2);
  if (i2 != NULL)
  {
    /* Found both markers, extract text. */
    const size_t mlen = i2 - (i1 + pl1);
    char* ret = malloc(mlen + 1);
    if (ret != NULL)
    {
      memcpy(ret, i1 + pl1, mlen);
      ret[mlen] = '\0';
      return ret;
    }
  }
  return NULL;
}

样品运行:

extract_between("foobarbaz", "foo", "bar", 0) = ""
extract_between("foobarbaz", "foo", "bar", 1) = NULL
extract_between("foobarbaz", "foo", "baz", 0) = "bar"
extract_between("foobarfoobarbaz", "foo", "bar", 1) = ""
extract_between("foobarfoobarbaz", "foo", "baz", 1) = "bar"
extract_between("foofoofoobarfoo", "foo", "bar", 2) = ""
extract_between("foofoofoobarfoo", "foo", "foo", 2) = "bar"
extract_between("foofoofoobarfoo", "foo", "bar", 3) = NULL