c - 在不丢失任何数据的情况下将一个字符串拆分为多个 X 字符串

标签 c string split

我正在尝试创建一种将字符串拆分为 X 个字符串的方法。现在我创建的方法的问题是,如果输入字符串不是一个完美的除法,字符串就会被截断,我会丢失原始字符串的一个片段。你能帮我修一下吗?

#define PARTSTRINGLEN 8;

void splitString(const char *text){
    const char **partString;
    int n = PARTSTRINGLEN;
    int i;
    size_t len = strlen(text);

    partString = malloc(sizeof(*partString) * len / n);

    for (i = 0; i < (len / n); i++)
    {
        partString[i] = strndup(text + n * i, (size_t) n);
        printf("%s\n", partString[i]);
    }
}

例如:char text[] = "this is a string used as example" 结果是:

this is ,
a string,
 used as,
 an exam.

相反,我寻求的实际结果是:

this is ,
a string,
 used as,
 an exam,
ple.

最佳答案

如果您有小于 PARTSTRINGLEN 的剩余片段,则您的循环必须长 1。必须处理适当的内存分配和释放。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define PARTSTRINGLEN 8

char ** splitString(const char *text, size_t len1){
    char **partString;
    int n = PARTSTRINGLEN;
    size_t i;

    partString = (char **) malloc( sizeof(*partString) * len1);

    for (i = 0; i < len1; i++)
    {
        partString[i] = strndup(text + n * i, (size_t) n);

        printf("%s\n", partString[i]);
    }

    return partString;
}

int main (void)
{
  char ** ptr;
  char *str = "this is a string used as an example";   
  size_t len = strlen(str); 

  size_t len1 = len/PARTSTRINGLEN;
  if(len%PARTSTRINGLEN) len1++;

  ptr = splitString(str,len1);

  for (size_t i = 0; i < len1; i++)
     free(ptr[i]);

  free(ptr);

  return 0; 
}

结果:

  this is                                                                                                                            
a string                                                                                                                           
 used as                                                                                                                           
 an exam                                                                                                                           
ple

关于c - 在不丢失任何数据的情况下将一个字符串拆分为多个 X 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49097845/

相关文章:

mysql - 文本字段

string - 如何以特定编号访问字符串中的char?

javascript - 需要使用JavaScript过滤掉字符串中重复的连续字符

c#:如何使用默认空格+一组附加分隔符拆分字符串?

python - 将列表拆分为子列表中的 n 个项目,并添加剩余部分

c - 局部变量如何存储在堆栈中?

c - x86 汇编代码中的指针引用

file - 如何根据行值拆分CSV文件

c - 函数参数数据类型错误

c - Linux 信号量初始化 : error implicit declaration of function 'semaphore_init'