我有一个函数,它将每行输入的所有单词作为单词数组返回,如下所示:
char **commands(const char *command){
char **commands_list;
int count,pos,len,i;
for(pos=0,count=0;;count++){
pos+= strspn(command+pos," \t\r\n");
if (command[pos] == '\0') break;
len = strcspn(command+pos," \t\r\n");
pos += len;
}
commands_list = malloc(sizeof(*commands_list) * (count+1));
if(commands_list == NULL) return NULL;
for(pos = 0, i=0;;i++){
pos += strspn(command+pos," \t\r\n");
if(command[pos] == '\0') break;
if(command[pos] == '>') break;
len = strcspn(command+pos," \t\r\n");
commands_list[i] = strndup(command+pos,len);
if (commands_list[i] == NULL){
while(i-->0) free(commands_list[i]);
free(commands_list);
return NULL;
}
pos+=len;
}
commands_list[i] = NULL;
return commands_list;
}
现在在另一个函数中,我想循环遍历这些单词中的每一个,并在有 > 的地方将它们分开。
例如,如果终端中的输入是 ls tests/folder-test>/tmp/output 那么返回的输出是
{"ls","tests/folder-test>/tmp/output"}
但我希望它将其转换为 {"ls","tests/folder-test"}
并返回 tmp/output 部分。
如果您的代码发送有效的字符**,则循环进入所有字符并在“>”上拆分的函数可能如下所示:
#include <stdio.h>
#include <string.h>
char **str_to_word_array(char *str, const char *sep)
{
char **text;
char *copy = strdup(str);
char *str_tok = strtok(copy, sep);
int size = 1;
int index = 0;
while (strtok(NULL, sep) != NULL)
size++;
free(copy);
copy = strdup(str);
text = malloc(sizeof(char *) * (size + 1));
str_tok = strtok(copy, sep);
while (str_tok != NULL) {
text[index] = str_tok;
index++;
str_tok = strtok(NULL, sep);
}
text[index] = NULL;
return text;
}
void get_all_splited(char **tab)
{
char **temp_tab = NULL;
char *sep = strup(">");
int len = 0;
for (int i = 0; tab[i]; i++) {
temp_tab = str_to_word_array(tab[i], sep);
for (len = 0; temp_tab[len]; len++);
if (len > 1) {
free(tab[i])
tab[i] = strdup(temp_tab[0])
printf("This value can be returned or stored into a tabe that you'll return %s", temp_tab[i]);
}
}
}
不要忘记释放所有内容并检查您的 char ** 是否有效。
更多信息请查看strtok手册