nixpix
nixpix

Reputation: 55

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

I was thinking something like this:

input string: dawddwamars#dawdjiawjd!fjejafi!djiajoa#jdawijd#

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

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.

Upvotes: 1

Views: 5613

Answers (3)

chux
chux

Reputation: 153478

If you must use 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.

Upvotes: 1

Tim Zimmermann
Tim Zimmermann

Reputation: 6420

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).

#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++;
        }
    }
}

Upvotes: 1

Jonathan Wood
Jonathan Wood

Reputation: 67193

scanf() has a lot of features that just aren't needed here.

To be more efficient, I would probably use strtok(), which seems ideal for this task.

Alternatively, I might just write C code to find the next # or ! using strchr() or a simple loop, and then just extract the tokens myself.

Upvotes: 0

Related Questions