gpt4 book ai didi

c - 将字符串拆分为 block 。

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

我正在尝试使用 C 将一个字符串分成 6 个 block ,但我遇到了困难。如果您输入 12 个字符长的字符串,它只会打印两个不寻常的字符。

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

void stringSplit(char string[50])
{
int counter = 0;
char chunk[7];

for (unsigned int i = 0; i < strlen(string); i++)
{
if (string[i] == ' ')
{
continue;
}

int lastElement = strlen(chunk) - 1;
chunk[lastElement] = string[i];
counter++;

if (counter == 6)
{
printf(chunk);
memset(chunk, '\0', sizeof chunk);
counter = 0;
}
}
if (chunk != NULL)
{
printf(chunk);
}

}

int main()
{
char string[50];
printf("Input string. \n");
fgets(string, 50, stdin);
stringSplit(string);
return(0);
}

我很感激任何帮助。

最佳答案

你的问题在

int lastElement = strlen(chunk) - 1;

首先,strlen 计算直到 NUL 字符的字符数。您的数组最初未初始化,因此这可能会导致问题。

假设您的数组中充满了 NUL,假设您在开头有 2 个字符,并且您希望放置第三个字符。请记住,您的 2 个字符分别位于位置 0 和 1。因此,strlen 将返回 2(您的字符串有 2 个字符),您减去一个,因此 lastElement 变量现在的值为 1。然后将第三个字符放在索引 1 处,从而覆盖已有的第二个字符。

另外,这是非常低效的,因为你每次都要计算字符数。但是等等,您已经知道您有多少个字符(您在 counter 中计算它们,不是吗?)。那么为什么不使用 counter 来计算应该放置新字符的索引呢? (注意不要重蹈覆辙)

关于c - 将字符串拆分为 block 。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42373252/

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