我正在尝试将一个字符附加到字符串。
我试过了
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/