gpt4 book ai didi

c - 将字符附加到字符串

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

我正在尝试将一个字符附加到字符串。

我试过了

char *string = malloc(strlen(text) * sizeof (char));
for(i=0, i <n; i++)
{
j = i;
while (j <= strlen(text))
{
string[strlen(string)] = text[i];
j = j + n;
}
string[strlen(string)] = '\0';
printf("%s", string);
string = "";
}

我的目标是创建 text 的变体。我遇到了这段代码的段错误。我做错了什么?

编辑:更清楚我想做的是:让我们说文本=“asdfghjk”对于 n = 3,我想要以下输出:

afj
sgk
dh

最佳答案

我会做类似的事情:

char *AppendCharToString( const char *orig, char newChar )
{
int oldLength = strlen(orig);
char *result = malloc( oldLength+2 ); // one byte for the new char, one for the terminator
strcpy(result, orig);
result[oldLength] = newChar;
result[oldLength+1] = 0;
return result;
}

关于c - 将字符附加到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7853795/

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