简体   繁体   English

在C中用scanf分割字符串

[英]Splitting strings with scanf in C

I have a string that has # and ! 我有一个带有#和!的字符串。 symbols throughout it. 整个符号。 My task is to separate all the content in between those symbols into new strings. 我的任务是将这些符号之间的所有内容分成新的字符串。 I don't know how many symbols there are going to be. 我不知道会有多少个符号。

Can I use the scanf function to separate them into strings 我可以使用scanf函数将它们分成字符串吗

I was thinking something like this: 我在想这样的事情:

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

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

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

Would this work? 这行得通吗? Or does someone have a method that is better. 还是有人有更好的方法。 I need to separate the string into substrings because i have to search for the longest common substring in those new strings. 我需要将字符串分成子字符串,因为我必须在这些新字符串中搜索最长的公共子字符串。

To get you started, here is some non-flexible code concerning number of substrings you will get out of the input string (strings array). 首先,这是一些与您从输入字符串(字符串数组)中取出的子字符串数量有关的非灵活代码。 As already mentioned, use strsep() (since strtok() is obsoleted by it, see man strtok ). 如前所述,请使用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++;
        }
    }
}

scanf() has a lot of features that just aren't needed here. scanf()具有许多此处不需要的功能。

To be more efficient, I would probably use strtok() , which seems ideal for this task. 为了提高效率,我可能会使用strtok() ,它似乎是完成此任务的理想选择。

Alternatively, I might just write C code to find the next # or ! 另外,我可能只是编写C代码来查找下一个#! using strchr() or a simple loop, and then just extract the tokens myself. 使用strchr()或简单的循环,然后自己提取令牌。

If you must use scanf() 如果必须使用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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM