大家好,我的问题是,如何将两个 C 风格的字符串合并为一个?
由于受到 C++ 做事方式(std::string)的影响,我从未接触过 C 风格的字符串,并且需要为我当前的开发项目了解更多关于它们的信息。例如:
char[] filename = "picture.png";
char[] directory = "/rd/";
//how would I "add" together directory and filename into one char[]?
提前致谢。
使用strcat()
.
见这里:http ://www.cplusplus.com/reference/clibrary/cstring/strcat/
#include <stdlib.h> #include <string.h> // ... 字符 * 全路径; 全路径 = malloc(strlen(目录)+strlen(文件名)+1); 如果(完整路径 == NULL) { //内存分配失败 } strcpy(完整路径,目录); strcat(完整路径,文件名);
你需要一个足够大的缓冲区,假设你在编译时没有filename
's 和' 的大小,你必须在运行时得到,就像这样directory
char *buf = (char *) malloc (strlen (filename) + strlen (directory) + 1);
if (!buf) { /* no memory, typically */ }
strcpy (buf, filename);
strcat (buf, directory);
请记住,您在较低级别工作,它不会自动为您分配内存。您必须分配足够的内存来保存两个字符串和一个空终止符,然后将它们复制到位。
一定要声明/分配一个char
足够大的数组来容纳filename
和directory
。然后,按照 xxpor 的建议使用strcat()
(或)。strncat()
您必须考虑您的“字符串”实际上是如何在内存中表示的。在 C 中,字符串是分配内存的缓冲区,以 0 字节结尾。
filename |p|i|c|t|u|r|e|0|
directory |/|r|d|/|0|
您需要一个新的内存空间来复制两个字符串的内存内容和最后一个 0 字节。
path |p|i|c|t|u|r|e|/|r|d|/|0|
这给出了这个代码:
int lenFilename = strlen(filename); // 7
int lenDirectory = strlen(directory); // 4
int lenPath = lenFilename + lenDirectory; // 11 I can count
char* path = malloc(lenPath + 1);
memcpy(path, filename, lenFilename);
memcpy(path + lenFilename, directory, lenDirectory);
path[lenPath] = 0; // Never EVER forget the terminating 0 !
...
free(path); // You should not forget to free allocated memory when you are done
(这段代码中可能有一个off-by-1错误,它实际上没有经过测试......现在是凌晨01:00,我应该去睡觉了!)