c - 如何在C代码中以20个字符为一组分隔字符
问题描述
在 C 语言中,我试图将存储的句子拆分为一个字符“嗨,我叫大卫。你叫什么名字?” 分成 20 个字符行:
“嗨,我叫大卫”
“。 你叫什么名字?”
起初,我正在考虑使用 for 循环分别打印出每个字符,但是,我开始意识到我只会打印前 20 个字符......对我能做什么有什么建议吗?
解决方案
只需strncpy
循环使用:
const char* str = "Hi, my name is David. What is your name?";
const size_t CHUNK_SIZE = 20;
size_t len = strlen(str);
size_t pos = 0;
while (pos < len)
{
char tmp[CHUNK_SIZE+1]; //+1 to leave room for null termination
strncpy(tmp, str+pos, CHUNK_SIZE);
tmp[CHUNK_SIZE] = '\0'; //null terminate end of buffer if needed
pos += CHUNK_SIZE;
printf("%s\n", tmp);
}
如果您只需要打印子字符串,则可以完全避免 tmp 缓冲区和 strncpy 的事情。让printf
精度说明符为您完成繁重的工作:
const char* str = "Hi, my name is David. What is your name?";
const size_t CHUNK_SIZE = 20;
size_t len = strlen(str);
size_t pos = 0;
while (pos < len)
{
printf("%.20s\n", str + pos);
pos += CHUNK_SIZE;
}
推荐阅读
- flutter - 如何显示双到 2 个小数点?
- forms - TYPO3 表单框架:以 HTML 和纯文本形式发送电子邮件
- java - java包和模块的允许名称
- android-studio - 更新到 Android Studio 3.5 版本后的新问题。运行应用程序时不会出现 ADB 设备选择屏幕 (SHIFT-F10)
- java - Maven、JavaFX、Launch4J-Maven-plugin - 如何捆绑 JRE?
- embedded-linux - 将 arm64 特定的内核头添加到 Linux 以刷新缓存
- reactjs - React Native Expo Offline App:如何从远程服务器更新本地数据库
- ruby-on-rails - 如何在更改与子表中不同记录的关系时触发销毁子项?
- ionic-framework - 升级 Ionic 3 - Ionic 4 CSS 复制问题
- batch-file - 如何将文件夹的每个子文件夹中除最新文件外的所有文件压缩为每个子文件夹一个 ZIP 文件?