我有一个char数组:
char* name = "hello";
Run Code Online (Sandbox Code Playgroud)
我想为该名称添加一个扩展名来实现它
hello.txt
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
name += ".txt" 不行
Dav*_*ill 59
看看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 */
Run Code Online (Sandbox Code Playgroud)
mct*_*ylr 19
我有一个char数组:
Run Code Online (Sandbox Code Playgroud)char* name = "hello";
不,你有一个字符串文字的字符指针.在许多用法中,您可以添加const修饰符,具体取决于您是否对名称指向的内容更感兴趣,还是字符串值" hello ".你不应该试图修改文字("你好"),因为可能会发生不好的事情.
要传达的主要内容是C没有正确的(或第一类)字符串类型."字符串"通常是字符(字符)数组,带有终止空('\ 0'或十进制0)字符,表示字符串的结尾,或指向字符数组的指针.
我建议阅读" 字符数组","C语言程序设计语言"第28页(第28页第二版).我强烈建议您阅读这本小书(<300页),以便学习C.
另外你的问题,第6 - 数组和指针和第8条- 字符和字符串中的Ç常见问题可能会有帮助.问题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;
}
Run Code Online (Sandbox Code Playgroud)
Sal*_*lv0 11
首先使用strcpy将当前字符串复制到更大的数组,然后使用strcat.
例如,您可以这样做:
char* str = "Hello";
char dest[12];
strcpy( dest, str );
strcat( dest, ".txt" );
Run Code Online (Sandbox Code Playgroud)
asprintf不是100%标准,但它可以通过GNU和BSD标准C库获得,所以你可能有它.它分配输出,因此您不必坐在那里计算字符.
char *hi="Hello";
char *ext = ".txt";
char *cat;
asprintf(&cat, "%s%s", hi, ext);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
216961 次 |
| 最近记录: |