所以,这里是函数:
int strinsert(char *dst, int len, const char *src, int offset)
我需要将我的 src
字符串的副本从位置 offset
插入到名为 dst
的字符串中。
参数 len
指定为数组 dst
保留的字符数。
代码的重要部分:
int strinsert(char *dst, int len, const char *src, int offset)
{
strncpy(dst, src+offset, len);
char buf[100];
strcpy(buf+len, src);
len += strlen(src) ;
strcpy(buf+len, dst+offset);
strcpy(dst, buf);
return 1;
}
还是觉得有点不对...
编辑:在有人误解之前,我只是在自学如何用 C 语言编程,我发现了这个练习。 btw,一维和二维数组我还真没找到什么好的学习资料,有没有好心人发一下?
最佳答案
这有点痛苦,但你真的必须构造一个新字符串,因为你不能真正如此轻松地随机移动内存位,而且我认为没有库函数可以做到这一点(有吗??) .像这样的东西:
int strinsert(char *dst, int len, const char *src, int offset)
{
char *new_string = new char[len];
int remaining = len;
// Check offset is not to long (+1 for null)
if (offset >= remaining)
offset = remaining;
// copy the pre-string from dest
strncpy(new_string, dest, offset);
// Calulate the remaining space
remaining -= offset;
// Add the insert string (with max chars remaining)
strncat(new_string, src, remaining);
// calc remaining space
remaining -= strlen(src);
// Add the post-string from dest (with max chars remaining)
strncat(new_string, dest, remaining);
// Finally copy the new_string into dest
strncpy(dest, new_string, len);
// free the memory
delete [] new_string;
}
注意:您可能需要更好地计算剩余空间,以防它变为负数...
编辑:用内存分配替换了可变长度数组(非法的...哎呀)
关于c - 如何将一个字符串的副本插入另一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19923109/