在C中,我试图将存储的句子分成一个字符“嗨,我的名字是David,你叫什么名字?”分成20个字符行:
“嗨,我叫大卫”
“你叫什么名字?”
起初,我在考虑使用for循环来分别打印每个字符,但后来我意识到我只打印前20个字符……我能做些什么,有什么建议吗?
发布于 2020-11-15 07:23: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 buffer和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;
}https://stackoverflow.com/questions/64839552
复制相似问题