【问题标题】:Reading a substring with spaces from a line in C从C中的一行读取带有空格的子字符串
【发布时间】:2014-03-14 16:15:14
【问题描述】:

我有一个带有标题信息的 ASCII 文件。标题中的一行是这样的:

# John Q. Public et al. 2014, to be submitted

我正在尝试获取名称。这是我的代码:

sscanf(line,"# %s et al.",NAME);

不幸的是,它只获得了名字。注意:名称可以是 1 个或多个以空格分隔的标记。基本上,我需要获取第一个哈希标记和“等”之间的所有内容。到单个字符串 (char*) 变量中。

有什么建议吗?谢谢。

【问题讨论】:

  • 读取带有fgets()的行然后解析它。
  • fgets 是更好的方法,但另一种方法是 scanf("%[^\n]", s) 阅读,直到您按下回车
  • OK ...所有作者都有“et al.”吗? “等”之后总是有一年吗?后跟一个逗号? ... ... ...

标签: c substring scanf


【解决方案1】:

以防万一您需要本地的东西:

bool readName(const char *line, char *name, int bufferSize)
{
    const char *hash = strstr(line, "# ");
    if(!hash)
        return false;
    const char *etal = strstr(hash+2, " et al.");
    if(!etal)
        return false;
    size_t numChars = min(etal-hash-2, bufferSize-1);
    strncpy(name, hash+2, numChars);
    name[numChars] = '\0';
    return true;
}

【讨论】:

  • strncpy(name, hash+2, min(etal-hash-2, bufferSize-1)); 不会 '\0' 终止 name
  • 谢谢chux,我更正了。我知道这个话题很老,但我不喜欢错误的代码。
【解决方案2】:

我会按照@pgm 的建议将该行读入内存,然后使用regular expressions 提取名称。在不知道您使用的平台/库的情况下,我无法给出具体示例。

【讨论】:

  • 该行已经从带有fgets() 的文件中读取。现在我有了这条线,我正试图从中得到名字。但我只能得到全名的第一个令牌。我正在使用 gnu 编译器在 Linux 上工作。
【解决方案3】:
#include <stdio.h>
#include <string.h>
#include <ctype.h>

void between(const char *str, const char *key1, const char *key2, char *out){
    char *from, *to, *p;
    *out = '\0';
    from = strstr(str, key1);
    if(!from) return ;
    from += strlen(key1);
    to = strstr(from, key2);
    if(!to) return ;//or rest ?
    while(isspace(*from))
        ++from;
    while(isspace(*--to))
        ;
    for(p = from; p <= to; )
        *out++ = *p++;
    *out = '\0';
}

int main(){
    char line[] = "# John Q. Public et al. 2014, to be submitted";
    char NAME[32];
    between(line, "#", "et al.", NAME);
    printf("<%s>\n", NAME);//<John Q. Public>

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    相关资源
    最近更新 更多