在 C 中连接 char 数组

标签 c string arrays

我有一个字符数组:

char* name = "hello";

我想为该名称添加一个扩展名

hello.txt

我该怎么做?

name += ".txt" 不起作用

最佳答案

看看 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 */
...
free(name_with_extension);

关于在 C 中连接 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2218290/

相关文章:

c - sem_wait 在我的程序中被忽略

有人可以使我从 C 中的指针查找数组长度的方法无效吗

c - 尝试编译简单的inotify程序

c - 如果包含数字,如何使整个字符串大写?

c++ - 使用isdigit比较unicode时出现调试断言失败错误

c# - 从二维数组中删除重复值

java - ClassCastException 将 Object[] 转换为 Trie.Node<V> 但不是 E[]

c++ - 在 ANTLR 生成的 C 解析器中使用 C++ 类型

java - Java 中的字符串拆分未按预期工作,给出了错误的结果

c - 使用指针从 C 中的函数调用数组元素