如何拆分字符串

时间:2010-12-11 14:25:36

标签: c split

HI,我想如何在没有#include

的情况下在c中拆分字符串

3 个答案:

答案 0 :(得分:1)

这样做的多种方式,我只是解释而不是为你写,因为这只能是一个功课(或自我提升练习,所以意图是相同的)。

  • 您可以将字符串拆分为多个字符串,然后将其重新分配到多维数组
  • 或者您只是在分隔符上剪切字符串并在适当的位置添加终端'\ 0',并将每个子字符串的起始地址复制到指针数组。

分裂的方法在两种情况下都类似,但在第二种情况下,您不需要分配任何内存(但修改原始字符串),而在第一种情况下,您可以创建每个子字符串的安全副本

你没有具体分裂,所以我不知道你是否想要削减子串,单个字符或潜在分隔符列表等等......

祝你好运。

答案 1 :(得分:0)

  1. 找到你要拆分它的点
  2. 制作两个足够大的缓冲区以包含数据
  3. strcpy()或手动执行(参见示例)
  4. 在这段代码中我假设你有一个字符串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" */
相关问题