繁体   English   中英

如何复制使用 strncpy 后剩余的字符串

[英]How to copy the string that remains after using 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 )以打印出来?

关于strncpy你应该了解的一件事是永远不要使用这个 function

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

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

如果要操作 memory,请使用memcpymemmove并注意 null 终止符。

事实上,字符串"Hello world!\n"有 13 个字符和一个 null 终止符,在 memory 中需要 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的更多信息:

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

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

此外, strncpy()不会NULL终止tmp ,如果您想要printf()puts()等功能正确地到 function ,则必须手动执行此操作。

#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;
}

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

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

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

char   someString[13] = "Hello World!\n";

您可以做的是推动您的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM