c - 有没有办法将字符串数组拆分为令牌上的字符串子数组
问题描述
"|"
基本上,有什么方法可以在 C 中的标记()之前和之后将字符串数组拆分为字符串数组。
一个例子如下所示。
char *input[] = {"hello","I","am","|","a","cool","|","guy"}
//code
结果是 3 个数组,包含
{"Hello","I","am"}
{"a","cool"}
{"guy"}
我尝试过strtok
,但这似乎将一个字符串拆分为多个片段,而不是将一个字符串数组拆分为新的、单独的字符串子数组。我也不知道究竟"|"
会有多少令牌存在,并且需要未知数量的新数组(可以肯定地说它会少于 10 个)。它们将被传递给,execvp
因此将其作为一个字符串并仅记住从哪里开始和停止查找是行不通的。
解决方案
它们将被传递给 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) */
推荐阅读
- operating-system - how can i print text in 16 bit real mode (graphical)?
- java - Several Main Methods (UI and Logic)
- javascript - Laravel : How to pass variable from View (javascript) to Controller?
- amazon-web-services - 从 aws-cdk 外部的 aws-cdk 堆栈访问 UserPoolId
- excel - InStr to extract all text before "[" if some cells contain "[" and some do not
- extjs - Extjs 7.0 日历标题未与列对齐
- python - 从json文件中提取信息,然后使用python排序
- linux - Bash 脚本 tee 命令语法问题
- php - ZIP文件夹上的PHP for循环在MySQL数据库中插入两倍的数据
- jsonpath - JSONPath 从数组中获取参数