c - 将字符串从 const char *const 数组复制到字符串(在 C 中)
问题描述
编辑:我添加了完整的代码。
我得到一个带有名称的数组并需要它们创建一个字符串,具体取决于存在多少个名称,这个字符串看起来不同。我试图用 strcpy 和 strcat 连接字符串,但它不起作用。
char* function1 (size_t n, const char *const names[n]) {
char *res;
switch (n) {
case 0:
res = "no one likes this";
break;
case 1:
strcpy(res, names[0]);
strcat(res, " likes this");
break;
case 2:
strcpy(res, names[0]);
strcat(res, " and ");
strcat(res, names[1]);
strcat(res, " like this");
break;
case 3:
strcpy(res, names[0]);
strcat(res, ", ");
strcat(res, names[1]);
strcat(res, " and ");
strcat(res, names[2]);
strcat(res, " like this");
break;
default:
strcpy(res, names[0]);
strcat(res, ", ");
strcat(res, names[1]);
strcat(res, " and ");
strcat(res, (char*) (n - 2));
strcat(res, " others like this");
break;
}
return res;
}
如何从数组中获取名称?我是否必须获取每个名称的长度,然后逐个字符地复制每个字符?
该函数调用如下:
int main(void) {
const char *const names[3] = {"John", "Peter", "Paul"};
char* res = function1(3, names);
printf("%s", res);
return 0;
}
结果应如下所示:
- 1 个名字:X 喜欢这个。
- 2 个名称:X 和 Y 像这样。
- 3 个名称:X、Y 和 Z 像这样。
- 4 和更多:X、Y 和“数字”更像这样。
我知道如何连接字符串,但很难将名称从数组中复制出来。这是来自教程中的 C 练习。
解决方案
字符 *res = "";
strcpy(资源,
这样的代码是无效的,它是未定义的行为。"string"
像但也只是""
不可变的字符串文字。你不能给他们写信。而且由于语言非常古老,它允许你做,而它应该只允许在 c++char *res = ""
中做类似的事情。const char *res = ""
要将字符串复制到某处,您必须拥有那个“某处”——一块空闲内存,它有足够的空间来保存结果。
如何从数组中获取名称?
遍历数组并“获取名称”。
void function1 (size_t n, const char *const names[n]) {
for (size_t i = 0; i < n; ++i) {
printf("Getting names[%zu]=%s\n", i, names[i]);
}
}
我是否必须获取每个名称的长度,然后逐个字符地复制每个字符?
如果要将这些字符串连接在一起,则必须逐个字符地复制它们。还包括用于分隔符的空间,例如空格。
#include <string.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
char *function1(size_t n, const char * const names[n]) {
// Calculate how much space we need
// for zero sentinel value and...
size_t len = 1;
// ...and for all the names and...
for (size_t i = 0; i < n; ++i) {
len += strlen(names[i]);
}
// ...and for space in between words.
if (n != 0) {
len += n - 1;
}
// Allocate memory. sizeof(*res) = sizeof(char) = 1
char *res = malloc(len * sizeof(*res));
if (res == NULL) {
// always handle errors
return NULL;
}
// Initialize with empty string.
res[0] = '\0';
for (size_t i = 0; i < n; ++i) {
// Concatenate the names.
strcat(res, names[i]);
if (i + 1 != n) {
// And remember about separating them.
strcat(res, " ");
}
}
return res;
}
int main(void) {
const char * const names[3] = {"John", "Peter", "Paul"};
char* res = function1(3, names);
if (res == NULL) {
return EXIT_FAILURE;
}
printf("Names concatenated with space as separator: %s\n",
res);
free(res);
}
推荐阅读
- c# - 数据模型依赖于另一个数据模型的属性时的数据绑定
- elasticsearch - elasticsearch中关键字类型为文本时如何使用term查询
- android - 如何动态更改依赖项?
- .net - Grafana PromQL 无法读取未定义的属性“结果”
- flutter - 自定义原材料按钮 - Flutter
- angular - 尝试 npm install 时标签名称“file-saver@2.0.1”无效
- angular - RXJS 和 typescript:有条件地使用服务器和客户端代码执行工作
- c# - 如何在 ASP.NET Core 中为 React SPA 自定义身份控制器?
- java - 获取与文件 java 关联的应用程序
- spring-boot - Spring Boot application.properties 无法从另一个属性文件中获取值