首页 > 解决方案 > 有没有办法将字符串数组拆分为令牌上的字符串子数组

问题描述

"|"基本上,有什么方法可以在 C 中的标记()之前和之后将字符串数组拆分为字符串数组。

一个例子如下所示。

char *input[] = {"hello","I","am","|","a","cool","|","guy"}

//code

结果是 3 个数组,包含

{"Hello","I","am"}
{"a","cool"}
{"guy"}

我尝试过strtok,但这似乎将一个字符串拆分为多个片段,而不是将一个字符串数组拆分为新的、单独的字符串子数组。我也不知道究竟"|"会有多少令牌存在,并且需要未知数量的新数组(可以肯定地说它会少于 10 个)。它们将被传递给,execvp因此将其作为一个字符串并仅记住从哪里开始和停止查找是行不通的。

标签: carraysstringsplit

解决方案


它们将被传递给 execvp

假设字符串包括要执行的程序(第一个参数execvp()),并且字符串将按照这个指针数组按照出现的顺序使用

char *input[] = {"hello","I","am","|","a","cool","|","guy"}

那么没有任何重复的可能的简单解决方案可能如下所示:

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

char * input[] = {"hello", "I", "am", "|", 
                  "a", "cool", "|",
                  "guy", "|"}; /* note the additional trailing `"|"`. */

int main(void)
{
  char ** pcurrent = input;
  char ** pend = pcurrent + sizeof input / sizeof *input;

  while (pcurrent < pend)
  {
    {
      char ** ptmp = pcurrent;
      while (ptmp < pend && **ptmp != '|')
      {
        ++ptmp;
      }

      *ptmp = NULL;
    }

    {
      pid_t pid = fork();
      if ((pid_t) -1) == pid)
      {
        perror("fork() failed");
        exit(EXIT_FAILURE);
      }

      if ((pid_t) 0) == pid) /* child */
      {
        execvp(pcurrent[0], pcurrent);
        perror("execvp() failed");
        exit(EXIT_FAILURE);
      }

      /* parent */
      pcurrent = ptmp + 1;
    }
  }  /* while (pcurrent < pend) */
}  /* int main(void) */

推荐阅读