操作 C 风格的字符串?
嘿大家, 我的问题是,如何将两个 C 风格字符串附加到一个字符串中?
由于受 C++ 处理方式 (std::string) 的影响,我从未接触过 C 风格的字符串,并且需要为我当前的开发项目了解更多有关它们的信息。例如:
char[] filename = "picture.png";
char[] directory = "/rd/";
//how would I "add" together directory and filename into one char[]?
提前致谢。
Hey all,
My question is, how do I append two C-style strings into one?
Being babied by the C++ way of doing things (std::string), I've never touched C-style strings and need to learn more about them for my current development project. For example:
char[] filename = "picture.png";
char[] directory = "/rd/";
//how would I "add" together directory and filename into one char[]?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用
strcat()
。请参阅此处: http://www.cplusplus.com/reference/clibrary/cstring/strcat /
Use
strcat()
.See here: http://www.cplusplus.com/reference/clibrary/cstring/strcat/
您需要一个足够大的缓冲区,假设您在编译时没有方便的文件名和目录大小,则必须在运行时获取,像这样
You need a big enough buffer, that, assuming you don't have
filename
's anddirectory
's size handy at compile-time, you must get at run-time, like so请记住,您正在较低级别工作,它不会自动为您分配内存。您必须分配足够的内存来保存两个字符串和一个空终止符,然后将它们复制到位。
Keep in mind you're working a lower level, and it's not going to allocate memory for you automatically. You have to allocate enough memory to hold the two strings plus a null terminator and then copy them into place.
请务必声明/分配一个足够大的
char
数组,以容纳filename
和directory
。然后,按照 xxpor 的建议使用strcat()
(或strncat()
)。Be sure to declare/allocate a
char
array large enough to hold bothfilename
anddirectory
. Then, usestrcat()
(orstrncat()
) as xxpor suggested.你必须考虑你的“字符串”在内存中实际上是如何表示的。在 C 中,字符串是分配内存的缓冲区,以 0 字节结尾。
您需要的是一个新的内存空间来将两个字符串的内存内容以及最后一个 0 字节复制在一起。
给出了这段代码:(
这段代码中可能有一个相差 1 的错误,它没有经过实际测试......现在是凌晨 01:00,我应该去睡觉了!)
You have to think how your "string" is actually represented in memory. In C, strings are buffers of allocated memory terminated by a 0 byte.
What you require is a new memory space to copy the memory content of both strings together and the last 0 byte.
Which gives this code:
(There may be an off-by-1 mistake in this code, it is not actually tested... It is 01:00am and I should go to sleep!)