c - 将字符串的字符存储在变量 C 中
问题描述
我有一个字符串
str = "hello"
str
我想创建一个新字符串,它是“he”的前两位数字。
我如何在 C 中做到这一点?
解决方案
使用strncpy(),如下所示:
#include <stdio.h>
#include <string.h>
int main(void) {
char src[] = "hello";
char dest[3]; // Two characters plus the null terminator
strncpy(dest, &src[0], 2); // Copy two chars, starting from first character
dest[2] = '\0';
printf("%s\n", dest);
return 0;
}
输出:
他
推荐阅读
- date - 如何计算 Pine Script 中两个日期(天数)之间的差异?
- elasticsearch - 如何在不通过 tls 传递 -k 的情况下卷曲 elasticsearch kubernetes 运算符?
- matlab - 在 for 循环中使用 struct 访问二叉搜索树
- android - 我可以在扩展小部件中使用列小部件吗?
- amazon-web-services - AWS EC2 用户数据在修改后不起作用
- html - 如何修复 div 中的左边距以在很多段落的中间工作
- python - Tkinter 动画标签文本作为 html 品牌
- django-views - Django-不在前端显示 PDF 页面
- javascript - 如何开发具有多个下拉菜单的站点内链接程序?
- java - Java 正则表达式,“”和“\\s\\s”之间的区别