Home > Blockchain >  How to get word from string containing numbers through sscanf?
How to get word from string containing numbers through sscanf?

Time:06-28

I have string "word123" need to extract only "word" using sscanf.

          char str[10];
          sscanf("word1233","%s", str);

CodePudding user response:

Depending on the requirements, I don't think this is the best way to do it, but if you want to do it this way, I would simply accept a string that ignores digits.

sscanf("word1233","%[^0123456789]", str);

You could also specify only the allowed characters:

sscanf("word1233","%[abcdefghijklmnopqrstuvwxyz]", str);

Note that that would only allow lower case letters.

Here is a method that might make more sense in many situations:

char str[10] = {0};
    
char *s = "word1234";
    
for(int i=0; s[i] && isalpha(s[i]); i  )
    str[i] = s[i];

Do note that this is dangerous if str is not big enough, but on the other hand, that goes for your method too. You could correct that with:

sscanf("word1233","%9[^0123456789]", str);

A similar thing needs to be done for the loop.

CodePudding user response:

You can use %[^...] to match only characters not in the brackets. Then you can list the digit characters there.

char str[10];
sscanf("word1233", "%[^0123456789]", str);
  • Related