首页 > 解决方案 > 如何复制使用 strncpy 后剩余的字符串

问题描述

我正在学习 C 并想了解如何在使用strncpy. 我想让字符串Hello World分成两行。

For example:

int main() {
    char someString[13] = "Hello World!\n";
    char temp[13];

    //copy only the first 4 chars into string temp
    strncpy(temp, someString, 4);

    printf("%s\n", temp);          //output: Hell
}

如何将剩余字符 ( o World!\n) 复制到新行中以打印出来?

标签: cstringstrncmp

解决方案


您应该了解的一件事strncpy永远不要使用此功能

的语义strncpy是违反直觉的,大多数程序员都很难理解。它令人困惑且容易出错。在大多数情况下,它不能完成这项工作。

在您的情况下,它会复制前 4 个字节,其余部分temp未初始化。temp您可能已经知道这一点,但仍然通过将toprintf作为字符串参数传递来调用未定义的行为。

如果您想操作内存,请使用memcpymemmove注意空终止符。

事实上,字符串"Hello world!\n"有 13 个字符和一个空终止符,需要 14 个字节的内存。定义char someString[13] = "Hello World!\n";是合法的,但它someString不是 C 字符串。

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

int main() {
    char someString[14] = "Hello World!\n";
    char temp[14];

    memcpy(temp, someString, 4); //copy only the first 4 chars into string temp
    temp[4] = '\0';              // set the null terminator
    printf("%s\n", temp);        //output: Hell\n

    strcpy(temp + 4, someString + 4);  // copy the rest of the string
    printf("%s\n", temp);        //output: Hello World!\n\n

    memcpy(temp, someString, 14); //copy all 14 bytes into array temp
    printf("%s\n", temp);        //output: Hello World!\n\n

    // Note that you can limit the number of characters to output for a `%s` argument:
    printf("%.4s\n", temp);      //output: Hell\n
    return 0;
}

您可以在此处阅读更多信息strncpy


推荐阅读