gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:18:24 24 4
gpt4 key购买 nike

我正在尝试创建一种将字符串拆分为 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com