Min Kim
Min Kim

Reputation: 113

Use sscanf() to truncate string

If I want to get a substring between "/" "@", this one will work:

char buf[512] ="" ;
char src[512] = "iios/12DDWDFF@122";

sscanf( src, "%*[^/]/%[^@]", buf);
printf("%s\n", buf);          //buf will be "12DDWDFF"  

How can I get same result from "//^&#@iios////12DDWDFF@@@@122/&*@(@///";

char buf2[512] ="" ;
char src[512] = "//^&#@iios////12DDWDFF@@@@122/&*@(@///";

sscanf(src, "%*[4][^/]/%[4][^@]", buf2);
printf("%s\n", buf2);         //buf2 gets nothing

or

sscanf(src, "%*[^////]/////%[^@@@@]", buf2);
printf("%s\n", buf2);         //buf2 gets nothing

Upvotes: 1

Views: 379

Answers (1)

ameyCU
ameyCU

Reputation: 16607

You can write your sscanf statement as follows -

if(sscanf(src,"%*[^0-9]%[^@]",buf2)==1)
 {
     //do something
 }

%*[^0-9] will read until number is encountered and then discard it , and %[^@] will read into buf2 until @ is encountered.

Demo

Upvotes: 4

Related Questions