c - 如何复制使用 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
是永远不要使用此功能。
的语义strncpy
是违反直觉的,大多数程序员都很难理解。它令人困惑且容易出错。在大多数情况下,它不能完成这项工作。
在您的情况下,它会复制前 4 个字节,其余部分temp
未初始化。temp
您可能已经知道这一点,但仍然通过将toprintf
作为字符串参数传递来调用未定义的行为。
如果您想操作内存,请使用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
:
推荐阅读
- javascript - 如何使用推送数组执行复选框的更新功能?
- java - 如何创建 POJO 类,该类在 Java 中为请求正文存储键值对列表?
- sql - 邮政编码上的 T-SQL 正则表达式
- perl - 有没有办法使用 perl NYTProf 获得简单的报告?
- python - 不能从其他函数调用函数 - Python
- postgresql - 来自 S3 存储桶的 pg_bulkload
- javascript - 如何将文件的内容保存到变量中,然后在请求中使用它?
- r - 查找从沿海点 A 到沿海点 B 的海上距离
- reactjs - inovua 反应数据网格 - 扩展行的唯一键警告
- javascript - 我正在尝试用噩梦制作一个网络抓取项目