高效地将一个字符串插入另一个字符串
我有
char aa[] = {“你好,!” };
char bb[] = { "World" };
如何使用 cstring 最有效地将 bb 插入到 aa 中?
I have
char aa[] = { "Hello, !" };
char bb[] = { "World" };
How to insert bb into aa the most efficiently with cstring ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
char *newStr = malloc(strlen(aa) + strlen(bb));
sprintf(newStr, "%s%s", aa, bb);
char *newStr = malloc(strlen(aa) + strlen(bb));
sprintf(newStr, "%s%s", aa, bb);
malloc
/new[]
)strncpy
/memcpy
)strcpy
/memcpy
)strncpy
/memcpy< /代码>)
malloc
/new[]
)strncpy
/memcpy
)strcpy
/memcpy
)strncpy
/memcpy
)最大程度的优化通常需要利用特定的要求。您可以使代码变得不那么通用,以提高速度(或其他一些指标)。你可能知道一些可以捷径的地方,而我们必须猜测。
下面的代码片段使用这些标头:
如果您想最大限度地提高性能,它将有助于为最终字符串预先分配足够的空间,插入后:
您不指示如何知道在哪里插入。对于我的示例代码,我将插入点定义为目标字符串的偏移量:
如果您提前知道任一字符串长度,则应该使用 const 而不是调用 strlen,后者必须扫描字符串。我不认为你有那么幸运。
memmove
函数正确处理重叠的源和目标:memcpy
在某些平台上速度更快,并且可以安全地用于在字符串之间进行复制:现在
aa
包含结果。如果您无法将
aa
预先分配到所需的大小,则:m
包含结果,并且最终可能需要释放
。请记住,如果有可能发生缓冲区溢出,您必须检查长度以避免内存损坏和可能的安全漏洞。
我希望这有帮助。
Maximum optimization usually requires taking advantage of the specific requirements. You make the code less general to gain speed (or some other metric). You may know some corner you can cut, while we have to guess.
Code fragments below use these headers:
If you want to maximize performance, it would help to pre-allocate enough space for the final string, post- insert:
You don’t indicate how you know where to insert. For my sample code I define the insert point as an offset into the destination string:
If you know either of the string lengths in advance you should use a const instead of calling strlen, which has to scan the string. Here I don’t’ assume you’re that lucky.
The
memmove
function properly handles overlapping source and destination:memcpy
is faster on some platforms and can be safely used to copy between strings:Now
aa
contains the result.If you can’t pre-allocate
aa
to the required size, then:m
contains the result and probably needs to befree
'd eventually.Remember if there is any chance for buffer overflow, you have to check lengths to avoid memory corruption and a possible security vulnerability.
I hope this helps.
那为什么你要把它标记为 C++ 呢?
Then why are you tagging this as C++?