c - 有没有办法将字符串数组拆分为 token 上的字符串子数组

标签 c arrays string split

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

示例如下。

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

//code

结果是3个数组,包含

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

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

最佳答案

They will be passed to 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) */

关于c - 有没有办法将字符串数组拆分为 token 上的字符串子数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56512842/

相关文章:

C 初学者 : Does scanf "receive" the EOF marker from standard input?

java - 如何从类创建对象数组,然后将它们传递给子类?

java - 初学者通过数组搜索

c - 在 C 中反转字符串

c++ - 如何将 ""替换为 "_"?

c - 不知道为什么程序崩溃

c - strcat 不影响全局字符串

c - 如何使用 C 通过串行端口将十六进制数据发送到自定义仪器中?

arrays - TypeScript 中混合类型的数组

c++ - 选择哈希键类型的理由