Search code examples
cstringscanf

Skip a char in string without stop with sscanf


I'm asking if I can use sscanf (scanf in general) to read a single character out to a string without reassembly, in C.

I tried multiple patterns without any success.

char a_word[10] = "a_word";
char b_word[10];

sscanf (a_word, "%%%", b_word);
b_word should contain: "a word".

As I pointed out just above, sure I could read in two separate chars and then strcat(), but can I avoid that.

Specifically, can I do it with just some tricky %format_specifier in one single char[] destination?
Thanks.


Solution

  • Not really.

    You can use"%[^_]_%[^_]" to match the prefix ("a") and suffix ("word") which requires two string arguments to write the result. You need the length of the prefix to figure out where to write the change (from _ to ) and the 2nd string into b_word. You can either extract that length ahead of time (sscanf(), strchr() or strcspn()) or split it into two sscanf() calls. This only works if you have 0 or 1 of the _:

    #include <stdio.h>
    
    int main(void) {
        char a_word[10] = "a_word";
        char b_word[10];
        int rv = sscanf(a_word, "%[^_]_", b_word);
        if(rv) b_word[rv++] = ' ';
        sscanf(a_word + rv, "%[^_]", b_word + rv);
        printf("%s\n", b_word);
    }
    

    Write a function instead:

    #include <stdio.h>
    #include <string.h>
    
    void strreplace(char *s, char from, char to) {
        while(*s++) if(*s == from) *s = to;
    }
    
    int main(void) {
        char a_word[10] = "a_word";
        char b_word[10];
        strcpy(b_word, a_word);
        strreplace(b_word, '_', ' ');
        printf("%s\n", b_word);
    }