首页 > 解决方案 > 如何在C代码中以20个字符为一组分隔字符

问题描述

在 C 语言中,我试图将存储的句子拆分为一个字符“嗨,我叫大卫。你叫什么名字?” 分成 20 个字符行:

“嗨,我叫大卫”

“。 你叫什么名字?”

起初,我正在考虑使用 for 循环分别打印出每个字符,但是,我开始意识到我只会打印前 20 个字符......对我能做什么有什么建议吗?

标签: cstringchar

解决方案


只需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;
}

推荐阅读