1

我正在学习 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) 复制到新行中以打印出来?

4

4 回答 4

2

您应该了解的一件事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

于 2021-02-21T23:39:58.920 回答
1

首先char someString[13],您没有足够的空间用于字符串Hello World\n,因为您有 13 个字符,但您至少需要 14 个字符,为 , 增加一个NULL byte字节'\0'。你最好让编译器决定数组的大小,这样就不会容易出现UB

要回答您的问题,您可以只使用printf()来显示字符串的剩余部分,您只需要指定一个指向您要开始的元素的指针。

此外,strncpy()不会NULL终止tmp,如果您想要类似printf()puts()正常运行的功能,您将不得不手动执行此操作。

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

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

    strncpy(temp,someString,4);

    temp[4] = '\0'; /* NULL terminate the array */

    printf("%s\n",temp);
    printf("%s",&someString[4]); /* starting at the 4th element*/

    return 0;
}
于 2021-02-21T22:40:06.897 回答
0

在您的情况下,您可以尝试以下操作:

char   temp2[13];
strncpy(temp2, &someString[4], 9);

顺便说一句,您缺少分号:

char   someString[13] = "Hello World!\n";
于 2021-02-21T22:26:55.750 回答
0

你可以做的是推动你的n角色指针并复制角色size - n

size_t n = 4; // nunmber caractere to copy first 
size_t size = 13; // string length

char someString[size] = "Hello World!\n";
char temp[size];
char last[size - n]; // the string that contain the reste

strncpy(temp, someString, n); // your copy
strncpy(last, someString + n, 13 - n); // copy of reste of the string
于 2021-02-21T22:28:11.750 回答