【发布时间】:2016-12-24 19:43:26
【问题描述】:
我正在编写一个函数来将字符串拆分为指向指针的指针,如果分隔符是空格,我只想拆分不在引号内的单词。例如Hello world "not split" 应该返回
Hello
world
"not split"
该函数以某种方式拆分引号内的单词,而不是拆分引号外的单词。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int is_quotes(char *s)
{
int i;
int count;
i = 0;
count = 0;
while (s[i])
{
if (s[i] == '"')
count++;
i++;
}
if (count == 0)
count = 1;
return (count % 2);
}
int count_words(char *s, char sep)
{
int check;
int i;
int count;
check = 0;
if (sep == ' ')
check = 1;
i = 0;
count = 0;
while (*s && *s == sep)
++s;
if (*s)
count = 1;
while (s[i])
{
if (s[i] == sep)
{
if (!is_quotes(s + i) && check)
{
i += 2;
while (s[i] != 34 && s[i])
i++;
}
count++;
}
i++;
}
return (count);
}
char *ft_strsub(char const *s, unsigned int start, size_t len)
{
char *sub;
sub = malloc(len + 1);
if (sub)
memcpy(sub, s + start, len);
return (sub);
}
char **ft_strsplit(char const *s, char c)
{
int words;
char *start;
char **result;
int i;
words = count_words((char *)s, c);
if (!s || !c || words == 0)
return (NULL);
i = 0;
result = (char **)malloc(sizeof(char *) * (words + 1));
start = (char *)s;
while (s[i])
{
if (s[i] == c)
{
if (is_quotes((char *)s + i) == 0 && c == ' ')
{
i += 2;
while (s[i] != '"' && s[i])
i++;
i -= 1;
}
if (start != (s + i))
*(result++) = ft_strsub(start, 0, (s + i) - start);
start = (char *)(s + i) + 1;
}
++i;
}
if (start != (s + i))
*(result++) = ft_strsub(start, 0, (s + i) - start);
*result = NULL;
return (result - words);
}
int main(int argc, char **argv)
{
if (argc > 1)
{
char **s;
s = ft_strsplit(argv[1], ' ');
int i = 0;
while (s[i])
printf("%s\n", s[i++]);
}
return 0;
}
当我使用hello world "hello hello" 运行此代码时,我得到以下信息
hello world
"hello
hello"
【问题讨论】:
-
@Olaf 抱歉,我的意思是指向指针
**。 -
使用调试器单步调试您的代码。
-
代码中没有
main函数。 -
我们不必弄清楚
count_words()的工作原理——你应该向我们展示相关代码。也可以显示main()函数;它不应该很大,并且会变成 MCVE (minimal reproducible example)。在ft_strsplit()你有:words = count_words((char *)s, c); if (!s || !c || words == 0) return (NULL);——count_words()是否处理s == 0或c == 0的情况?尽快摆脱不可能的事情。考虑在运行时检查之前添加一个assert(s != 0 && c != 0);断言。 -
对不起,我忘了包括
count_words()和main()。