将字符串拆分为多个X字符串而不会丢失任何数据

问题描述 投票:1回答:1

我正在尝试创建一个将字符串拆分为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 an example"结果是:

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

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

this is ,
a string,
 used as,
 an exam,
ple.
c string split
1个回答
1
投票

如果剩下的片段少于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
© www.soinside.com 2019 - 2024. All rights reserved.