在C中连接char数组
string arrays (5)
我有一个char数组:
char* name = "hello";
不,你有一个字符串文字的字符指针。 在许多用法中,您可以添加const修饰符,具体取决于您是否对名称指向的内容更感兴趣,还是字符串值“ hello ”。 你不应该试图修改文字(“你好”),因为可能会发生不好的事情 。
要传达的主要内容是C没有正确的(或第一类 )字符串类型。 “字符串”通常是字符(字符)数组,带有终止空('\ 0'或十进制0)字符,表示字符串的结尾,或指向字符数组的指针。
我建议阅读“ 字符数组” , “C语言程序设计语言”第28页(第28页第二版)。 我强烈建议您阅读这本小书(<300页),以便学习C.
除了你的问题,第6节 - 数组和指针和第8节 - C FAQ的 字符和字符串可能会有所帮助。 问题6.5和8.4可能是开始的好地方。
我希望这可以帮助您理解为什么您的摘录不起作用。 其他人已经概述了使其发挥作用所需的变化。 基本上你需要一个char数组(一个字符数组),它足以存储整个字符串的终止(结束)'\ 0'字符。 然后你可以使用标准的C库函数strcpy(或者更好的strncpy)将“Hello”复制到其中,然后你想使用标准的C库strcat(或更好的strncat)函数进行连接。 您将需要包含string.h头文件来声明函数声明。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
char filename[128];
char* name = "hello";
char* extension = ".txt";
if (sizeof(filename) < strlen(name) + 1 ) { /* +1 is for null character */
fprintf(stderr, "Name '%s' is too long\n", name);
return EXIT_FAILURE;
}
strncpy(filename, name, sizeof(filename));
if (sizeof(filename) < (strlen(filename) + strlen(extension) + 1) ) {
fprintf(stderr, "Final size of filename is too long!\n");
return EXIT_FAILURE;
}
strncat(filename, extension, (sizeof(filename) - strlen(filename)) );
printf("Filename is %s\n", filename);
return EXIT_SUCCESS;
}
我有一个char数组:
char* name = "hello";
我想为该名称添加一个扩展名来实现它
hello.txt
我怎样才能做到这一点?
name += ".txt"
不起作用
asprintf
不是100%标准,但它可以通过GNU和BSD标准C库获得,所以你可能拥有它。 它分配输出,因此您不必坐在那里计算字符。
char *hi="Hello";
char *ext = ".txt";
char *cat;
asprintf(&cat, "%s%s", hi, ext);
您可以使用sprintf()函数连接字符串。 在您的情况下,例如:
char file[80];
sprintf(file,"%s%s",name,extension);
你将在“文件”中结束连接字符串。
看看strcat函数。
特别是,你可以试试这个:
const char* name = "hello";
const char* extension = ".txt";
char* name_with_extension;
name_with_extension = malloc(strlen(name)+1+4); /* make space for the new string (should check the return value ...) */
strcpy(name_with_extension, name); /* copy name into the new var */
strcat(name_with_extension, extension); /* add the extension */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *name = "hello";
int main(void) {
char *ext = ".txt";
int len = strlen(name) + strlen(ext) + 1;
char *n2 = malloc(len);
char *n2a = malloc(len);
if (n2 == NULL || n2a == NULL)
abort();
strlcpy(n2, name, len);
strlcat(n2, ext, len);
printf("%s\n", n2);
/* or for conforming C99 ... */
strncpy(n2a, name, len);
strncat(n2a, ext, len - strlen(n2a));
printf("%s\n", n2a);
return 0; // this exits, otherwise free n2 && n2a
}