简体   繁体   中英

How can I get a part of string with sscanf() function?

Currently I'm following a C book and I can not resolve one exercise. Given that I spend more than 1 day at this point, I need some help/ideas.

"Assume that str is a string that contains a "sales rank" immediately preceded by the # symbol(other characters may precede the # and/or follow the sales rank). A sales rank is a series of decimal digits possibly containing commas, such as the following examples:

 989 24,675 1,162,620 

Write a call of sscanf that extracts the sales rank (but not the # symbol) and stores it in a string variable named sales_rank."

What I understand that it's needed:

for example if we have:

     char *str = "ana are mer2,1#3lala";

sales_ranks should be: "2,1"

in case of:

     char *str = "ana ar#e mer2,1a3lala";

sales_ranks is an empty string.

I found here ( http://cboard.cprogramming.com/c-programming/149330-getting-part-string-sscanf.html ) few useful informations but it is not the correct solution. They interpreted the exercise in a wrong approach like this:

     char *str = "ana are mer2,1#3lala";

sales_ranks is "3" which is OK but not what requested by author: "sales rank" immediately preceded by the # symbol

EDITED:

I misunderstood who by who is preceded. :| (So the solution exposed in the link is OK)

Actually I spend all this time to find a solution for this kind of pattern: "{decimal}#" :)

but it is possible and so? I mean if it is possible that: # symbol immediately preceded by the "sales rank"

You can use sscanf with the %[] and %* syntaxes to achieve this:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    char sales_rank[200];
    char *str;

    sales_rank[0] = 0;
    str = "ana are mer2,1#3lala";

    sscanf(str, "%*[^#]#%199[0-9,]", sales_rank);
    printf("sales_rank=%s\n", sales_rank);

    return 0;
}

The %*[^#] will skip the chars before the # , ignoring them and the %199[0-9,] will store the sales_rank string in the variable. The matching process will stop after reading sales_rank . Any additional characters will be ignored.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM