HI,我想如何在没有#include
的情况下在c中拆分字符串答案 0 :(得分:1)
这样做的多种方式,我只是解释而不是为你写,因为这只能是一个功课(或自我提升练习,所以意图是相同的)。
分裂的方法在两种情况下都类似,但在第二种情况下,您不需要分配任何内存(但修改原始字符串),而在第一种情况下,您可以创建每个子字符串的安全副本
你没有具体分裂,所以我不知道你是否想要削减子串,单个字符或潜在分隔符列表等等......
祝你好运。答案 1 :(得分:0)
在这段代码中我假设你有一个字符串str []并想在第一个逗号分割它:
for(int count = 0; str[count] != '\0'; count++) {
if(str[count] == ',')
break;
}
if(str[count] == '\0')
return 0;
char *s1 = malloc(count);
strcpy(s1, (str+count+1)); // get part after
char *s2 = malloc(strlen(str) - count); // get part before
for(int count1 = 0; count1 < count; count1++)
s2[count1] = str[count1];
得到了吗? ;)
答案 2 :(得分:0)
假设我完全控制了函数原型,我会这样做(将它作为单个源文件(没有#includes )并编译,然后链接到项目的其余部分)< / p>
如果#include <stddef.h>
是“没有#include”内容的一部分(但不应该),那么请使用下面代码中的size_t
代替unsigned long
#include <stddef.h>
/* split of a string in c without #include */
/*
** `predst` destination for the prefix (before the split character)
** `postdst` destination for the postfix (after the split character)
** `src` original string to be splitted
** `ch` the character to split at
** returns the length of `predst`
**
** it is UB if
** src does not contain ch
** predst or postdst has no space for the result
*/
size_t split(char *predst, char *postdst, const char *src, char ch) {
size_t retval = 0;
while (*src != ch) {
*predst++ = *src++;
retval++;
}
*predst = 0;
src++; /* skip over ch */
while ((*postdst++ = *src++) != 0) /* void */;
return retval;
}
使用示例
char a[10], b[42];
size_t n;
n = split(b, a, "forty two", ' ');
/* n is 5; b has "forty"; a has "two" */