我正在学习 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
是永远不要使用此功能。
strncpy
的语义是反直觉的,大多数程序员都很难理解。这是令人困惑且容易出错的。在大多数情况下,它不起作用。
在您的情况下,它会复制前 4 个字节,并留下
temp
的其余部分未初始化。您可能已经知道这一点,但仍然通过将 temp
作为字符串参数传递给 printf
来调用未定义的行为。
如果你想操纵内存,请使用
memcpy
和 memmove
并小心空终止符。
事实上,字符串
"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
的更多信息:
首先,
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;
}
顺便说一下,你漏掉了一个分号:
char temp2[13];
strncpy(temp2, &someString[4], 9);
char someString[13] = "Hello World!\n";
字符的指针并复制
n
字符:size - n