c - 删除最后一个字符,然后连接两个字符串

标签 c arrays string char concatenation

以下是从第一个字符串中删除最后一个字符,然后将其与第二个字符串连接的可接受方法吗?

char *commandLinePath = server_files_directory;
commandLinePath[strlen(commandLinePath)-1] = 0;

char fullPath[strlen(commandLinePath) + strlen(requestPath)];
strcpy(fullPath, commandLinePath);
strcat(fullPath, requestPath);

让我们假设 server_files_directory 没问题 (char *) 并且已经初始化。

我担心的是:删除部分是否正确以及生成的全路径的大小是否正确等。

最佳答案

这是 Not Acceptable ,因为在 fullPath 中没有空间来存储终止空字符。

声明应该是(add +1)

char fullPath[strlen(commandLinePath) + strlen(requestPath) + 1];

更新: 不破坏 server_files_directory 指向的替代方法:

size_t len1 = strlen(commandLinePath);
size_t len2 = strlen(requestPath);
char fullPath[len1 + len2]; /* no +1 here because one character will be removed */
strcpy(fullPath, commandLinePath);
strcpy(fullPath + len1 - 1, requestPath);

关于c - 删除最后一个字符,然后连接两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35695847/

相关文章:

c - 联机帮助页 scandir() 原型(prototype)怪异

c - 打印数组中的字符串时出现奇怪的字符?

java - 用数组声明微调器的简单方法

java - 为什么我无法创建自定义 String 类的实例,而我能够创建自定义 System 类的实例

javascript - 检测字符串上的 html 标签,获取值并删除 javascript 中 html 标签内的值

c# - 如何在 C/C++ 代码中使用 C# 结构体数组初始化?

c++ - 特定线程上的 gdb nostop SIGSEGV

c - string.withCString 和 UnsafeMutablePointer(变异 : cstring) wrapped into a function

C:初始化字符指针(字符串)数组并使用 fgets 遍历文件以将值放入这些字符串

php - 给定一组常数因子,在字符串中搜索字符串的最快方法