2
votes

Let's have this code

char input[] = "key: value";
char key[32], value[32];
sscanf(input, "%31[^:]:%*[ ]%31s", key, value);

There can be zero or more spaces after the :, I'd like to store the key ond value into c-string variables. The code above can work with one or more spaces, but tough luck with zero spaces.

Is there a simple way how to parse such strings? No necessarily sscanf, but I'd like to avoid regex.

Edit

I found a reference supporting the accepted answer (what an useful, but non-intuitive feature):

the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).

1
@PaulRoub: the situations are related, but I think this is different from the possible duplicate. In particular, there is a simple solution to this question; I don't think there's an alternative to the 'try it twice if necessary' answer in the other question.Jonathan Leffler
I would suggest using strstr to find the ':' replace the ':' with '\0' then strncpy() to get the first string. then using the previously acquired ptr to the '\0', step forward to the next non ' ' char, then perhaps sscanf() to retrieve that second string. Another method would be to use strtok()user3629249

1 Answers

6
votes

Just use "%31[^:]:%31s".

The %s conversion specification skips leading blanks anyway, and stops at the first blank after one or more non-blanks.

If you decide you need blanks in the second field, but not the leading blanks, then use:

"%31[^:]: %31[^\001]"

(assuming it is unlikely that your string contains control-A characters that you're interested in). The blank in the format string skips zero or more blanks (strictly, zero or more white space characters).