【问题标题】:C - split stringC - 拆分字符串
【发布时间】:2021-05-08 18:05:57
【问题描述】:

如果我想把它变成 4 个单词,我该如何处理这个字符串。如果我使用 sscanf ,它会将“面罩”一词分成两部分。或者可以以某种方式使用 sscanf 来防止这种情况发生?

输入:

2021-01-01 2021-7-1 'Face masks' "Wear everywhere"
2000-08-05 2010-8-8 LOCKDOWN 'xxxxx'

输出:

2021-01-01
2021-7-1 
'Face masks' 
"Wear everywhere"
....

【问题讨论】:

  • 您可以使用%[^'\"] 来匹配不包含引号的字符串。
  • 但如果引号是可选的,这将不起作用。 scanf() 不是通用解析器。听起来您需要编写代码来识别所有不同的可能格式。
  • 如果允许修改字符串,可以先用空格替换引号。
  • @Devolus:如果你这样做,你就无法分辨第三个单词在哪里结束,第四个单词从哪里开始:)
  • 啊,我误会了。

标签: c string char scanf


【解决方案1】:

scanf() 功能不足以满足您的目的,因为可选引号和可能的空词(''"")。

这是一个通用的手动编码解析器:

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

// split a string into up to count words stored in a 2D array of char
int split(char output[][100], int count, const char *str) {
    // recognises space separated words and quoted content without
    // embedded quotes of the same type. Quotes are stripped in output.
    for (int i = 0; i < count; i++) {
        const char *start;
        int len;

        str += strspn(str, " \t\f\v\r\n");
        if (*str == '\0')
            return i;
        if (*str == '\'') {
            start = ++str;
            len = strcspn(str, "\'");
            str += len;
            str += (*str == '\'');
        } else
        if (*str == '\"') {
            start = ++str;
            len = strcspn(str, "\"");
            str += len;
            str += (*str == '\"');
        } else {
            start = str;
            len = strcspn(str, " \t\f\v\r\n");
            str += len;
        }
        snprintf(output[i], sizeof(output[i]), "%.*s", len, start);
    }
}

【讨论】:

  • 谢谢你,这是我一直在努力的:)
  • 我会使用像this 这样的开关来避免代码重复
  • @AyxanHaqverdili:对代码进行因式分解很诱人,但消除了编译器为常量字符串内联 strcspn() 的机会,我还没有看到他们这样做,但这是可能的,并且对单个字符串很有用字符串。
猜你喜欢
  • 2017-06-16
  • 2011-02-13
  • 2011-11-25
  • 1970-01-01
  • 1970-01-01
  • 2021-12-21
相关资源
最近更新 更多