简体   繁体   English

操纵C风格的琴弦?

[英]Manipulating C-style strings?

Hey all, My question is, how do I append two C-style strings into one? 大家好,我的问题是,如何将两个C样式字符串附加到一个字符串中?

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. 被C ++的处事方式(std :: string)困扰,我从未接触过C风格的字符串,并且需要为我当前的开发项目了解更多有关它们的信息。 For example: 例如:

 char[] filename = "picture.png";
 char[] directory = "/rd/";
 //how would I "add" together directory and filename into one char[]?

Thanks in advance. 提前致谢。

#include <stdlib.h>
#include <string.h>

// ...

char * fullpath;

fullpath = malloc(strlen(directory)+strlen(filename)+1);
if (fullpath == NULL)
{
  // memory allocation failure 
}
strcpy(fullpath, directory);
strcat(fullpath, filename);

You need a big enough buffer, that, assuming you don't have filename 's and directory 's size handy at compile-time, you must get at run-time, like so 您需要足够大的缓冲区,假设在编译时没有方便的filenamedirectory大小,则必须在运行时获取,例如

char *buf = (char *) malloc (strlen (filename) + strlen (directory) + 1);
if (!buf) { /* no memory, typically */ }
strcpy (buf, filename);
strcat (buf, directory);

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. 您必须分配足够的内存来容纳两个字符串以及一个空终止符,然后将它们复制到位。

Be sure to declare/allocate a char array large enough to hold both filename and directory . 确保声明/分配一个足以容纳filenamedirectorychar数组。 Then, use strcat() (or strncat() ) as xxpor suggested. 然后,使用xxpor建议使用strcat() (或strncat() )。

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. 在C语言中,字符串是分配的内存缓冲区,以0字节结尾。

filename  |p|i|c|t|u|r|e|0|
directory |/|r|d|/|0|

What you require is a new memory space to copy the memory content of both strings together and the last 0 byte. 您需要一个新的存储空间来将两个字符串的存储内容和最后一个0字节一起复制。

path      |p|i|c|t|u|r|e|/|r|d|/|0|

Which gives this code: 给出以下代码:

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

(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!) (此代码中可能存在偏离1的错误,尚未经过实际测试...现在是凌晨01:00,我应该入睡!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM