You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何捕获空格与引号内的内容?C语言strtok()优化需求

解决方案:处理空格分隔与引号包裹的字符串分割

需求说明

需要将输入字符串按规则分割:

  • 普通单词以空格分隔,作为单个项
  • 双引号包裹的内容(包含内部空格)作为单个整体,且输出时去掉引号

输入示例:

The Brown "Fox Jumps Over" "The Lazy" Dog

原代码使用strtok()按空格分割,会错误拆分引号内的内容,期望输出为:

The
Brown
Fox Jumps Over
The Lazy
Dog

实现代码

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main() {
    char command[BUFSIZ];
    char *ptr = command;
    char *token_start;
    int in_quote = 0;

    // 读取输入并去除末尾换行符
    if (fgets(command, BUFSIZ, stdin) == NULL) {
        return 1;
    }
    command[strcspn(command, "\n")] = '\0';

    while (*ptr != '\0') {
        // 跳过前置空格
        while (isspace((unsigned char)*ptr)) {
            ptr++;
        }
        if (*ptr == '\0') {
            break;
        }

        token_start = ptr;
        if (*ptr == '"') {
            // 进入引号模式,跳过起始引号
            in_quote = 1;
            ptr++;
            token_start = ptr;
            // 扫描到结束引号为止
            while (*ptr != '\0' && *ptr != '"') {
                ptr++;
            }
            // 替换结束引号为字符串终止符
            if (*ptr == '"') {
                *ptr = '\0';
                ptr++;
            }
            in_quote = 0;
        } else {
            // 非引号模式,扫描到空格或引号为止
            while (*ptr != '\0' && !isspace((unsigned char)*ptr) && *ptr != '"') {
                ptr++;
            }
            // 分割当前token
            if (*ptr != '\0') {
                *ptr = '\0';
                ptr++;
            }
        }

        // 输出提取的内容
        printf(" %s\n", token_start);
    }

    return 0;
}

代码逻辑说明

  1. 输入预处理:用strcspn()移除fgets()读入的末尾换行符,避免干扰分割逻辑。
  2. 双模式扫描:通过指针遍历字符串,区分两种处理逻辑:
    • 非引号模式:从非空格字符开始,直到遇到空格或引号,用'\0'分割出单个单词。
    • 引号模式:遇到起始引号后,跳过引号并扫描至结束引号,将结束引号替换为'\0',直接提取引号内的内容(自动去除首尾引号)。
  3. 空格过滤:每次提取内容前先跳过连续空格,避免生成空的分割项。

内容的提问来源于stack exchange,提问作者mcsmachado

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 01:32:46