首页 > 解决方案 > 将字符串的字符存储在变量 C 中

问题描述

我有一个字符串

str = "hello"

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

我如何在 C 中做到这一点?

标签: cstring

解决方案


使用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;
}

输出:


推荐阅读