【问题标题】:Splitting strings with scanf in C在 C 中使用 scanf 拆分字符串
【发布时间】:2013-12-17 23:47:36
【问题描述】:

我有一个包含 # 和 ! 的字符串贯穿其中的符号。我的任务是将这些符号之间的所有内容分成新的字符串。我不知道会有多少符号。

我可以使用scanf函数将它们分成字符串吗

我在想这样的事情:

输入字符串:dawddwamars#dawdjiawjd!fjejafi!djiajoa#jdawijd#

字符 s1[20], s2[20], s3[20], s4[20], s5[20];

scanf("%s[^!][^#]%s[^!][^#]%s[^!][^#]%s[^!][^#]%s[^ !][^#]", s1, s2, s3, s4, s5);

这行得通吗?或者有人有更好的方法。 我需要将字符串分成子字符串,因为我必须在这些新字符串中搜索最长的公共子字符串。

【问题讨论】:

  • scanf("%[^!#]%*[!#]%[^!#]%*[!#]%[^!#]%*[!#]%[^!#]%*[!#]%[^!#]%*[!#]", s1, s2, s3, s4, s5);

标签: c string input split scanf


【解决方案1】:

为了让您开始,这里有一些关于您将从输入字符串(字符串数组)中获得的子字符串数量的非灵活代码。如前所述,使用strsep()(因为strtok()已被它淘汰,请参阅man strtok)。

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

int main() {
    char* str;
    char* token;
    char* temp;
    char strings[10][20];
    int i = 0;
    str = strdup("dawddwamars#dawdjiawjd!fjejafi!djiajoa#jdawijd#");

    printf("%s\n", str);
    while ((token = strsep(&str, "#")) != NULL) {
        temp = strdup(token);
        while ((token = strsep(&temp, "!")) != NULL) {
            printf("%s\n", token);
            strcpy(strings[i], token);
            i++;
        }
    }
}

【讨论】:

    【解决方案2】:

    如果您必须使用scanf()

    #define Fmt1   "%19[^#!]"
    #define Sep1   "%*[#!]"
    char s1[20], s2[20], s3[20], s4[20], s5[20];
    int count = scanf(" " Fmt1 Sep1 Fmt1 Sep1 Fmt1 Sep1 Fmt1 Sep1 Fmt1, 
        s1, s2, s3, s4, s5);
    // count represents the number of successfully scanned strings.
    // Expected range 0 to 5 and EOF.
    

    【讨论】:

    • @BLUEPIXY 不太引起你的关注,请详细说明。
    • @BLUEPIXY 除了允许前导空格和将字符串长度限制为 19 之外,这类似于您的 scanf("%[^!#]%... 建议。不知道你所说的“5 号”是什么意思。它是否只接受最多 5 个已解析的字符串?
    • 再也不用担心每次了。
    【解决方案3】:

    scanf() 有很多这里不需要的功能。

    为了提高效率,我可能会使用strtok(),这似乎非常适合这项任务。

    或者,我可能只是编写 C 代码以使用 strchr() 或简单循环来查找下一个 #!,然后自己提取标记。

    【讨论】:

      猜你喜欢
      • 2012-03-01
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      • 2011-11-04
      • 2015-06-29
      相关资源
      最近更新 更多