C语言分词问题:实现遇逗号/句号换行且引号内不拆分
C语言分词代码修改方案
核心修改逻辑
针对需求(逗号/句号单独换行拆分、引号内内容不拆分),核心调整点是:
- 在非引号状态下,将逗号(
,)和句号(.)作为独立分隔符处理:遇到时先输出已收集的单词,再单独输出该标点并换行 - 保留原有引号内内容不拆分的逻辑,确保引号内的标点不会被强制拆分
修改后的完整代码
#include <stdio.h> int main() { char input[] = "This is an apple.\"How are you doing? GREAT!!\""; char buf[256]; int idx = 0; int in_quote = 0; for (int i = 0; input[i] != '\0'; i++) { char c = input[i]; if (c == '"') { // 处理引号切换:先输出当前缓存的内容,再处理引号包裹的文本 if (in_quote) { buf[idx++] = c; buf[idx] = '\0'; printf("%s\n", buf); idx = 0; in_quote = 0; } else { if (idx > 0) { buf[idx] = '\0'; printf("%s\n", buf); idx = 0; } buf[idx++] = c; in_quote = 1; } } else if (in_quote) { // 引号内字符直接加入缓存 buf[idx++] = c; } else if (c == ' ' || c == ',' || c == '.') { // 非引号状态下,处理分隔符 if (idx > 0) { buf[idx] = '\0'; printf("%s\n", buf); idx = 0; } // 逗号/句号单独输出换行 if (c == ',' || c == '.') { printf("%c\n", c); } } else { // 普通字符加入缓存 buf[idx++] = c; } } // 处理最后剩余的缓存内容 if (idx > 0) { buf[idx] = '\0'; printf("%s\n", buf); } return 0; }
测试输出
运行后输出与期望一致:
This is an apple . "How are you doing? GREAT!!"
内容的提问来源于stack exchange,提问作者mann
相关产品推荐
相关产品推荐

