【问题标题】:Store characters of a string in a variable C [duplicate]将字符串的字符存储在变量C中[重复]
【发布时间】:2018-12-01 18:18:21
【问题描述】:

我有一个字符串

str = "hello"

我想创建一个新字符串,它是str“he”的前两位数字。

如何在 C 中做到这一点?

【问题讨论】:

  • 参见 strcpy()。只需输入man strcpy
  • @JoyAllen strcpy 复制整个字符串。 OP 只想要字符串的一部分,所以strncpy 更合适。
  • 如果您使用的是 Windows,请使用 strncpy_s 而不是 strncpy。
  • 我已经坐在我的电脑前超过 8 个小时了,今天我很新,只是试图理解神秘的 C 手册是一个挑战。我来这里是为了尝试用简单的英语获得一些东西,因为我很挣扎,因为我无法理解我已经在 stackoverflow 上查看过的其他内容。感谢您的帮助

标签: c string


【解决方案1】:

使用strncpy(),像这样:

#include <stdio.h>
#include <string.h>

int main(void) {
    char src[] = "hello";
    char dest[3]; // Two characters plus the null terminator

    strncpy(dest, &src[0], 2); // Copy two chars, starting from first character
    dest[2] = '\0';

    printf("%s\n", dest);
    return 0;
}

输出:

【讨论】:

  • 原始海报没有说明他是追求跨平台解决方案还是特定操作系统,但是如果他/她正在为 Windows 开发(并使用 MS 编译器),strncpy_s 是解决 strncpy 的方法。 strncpy_s 在技术上比 strncpy 更安全的原因是您必须指定目标的缓冲区大小,因此如果正确使用例程,您将不太容易受到潜在缓冲区溢出的影响。附带说明一下,如果我没记错的话, strncpy_s 实际上也应该为您处理空终止符。
猜你喜欢
  • 2020-09-20
  • 2016-08-24
  • 1970-01-01
  • 2013-10-05
  • 1970-01-01
  • 1970-01-01
  • 2016-08-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多