【大风】【Decode the string】代码分享:sscanf函数

Description

XiaoMing is a student of BigMount Middle School. One day, he wants to send a very very long message to his friend, Bob. His SIM card is China Mobile. As we all know, the fee of cellphone data plan is very expensive. To save money, he thinks of an idea to shorten the message. He uses a number to indicate how many times of the letter before appears.

For example, he replaces “aaa” with “a3”. (3 indicates there are three ‘a’)

After sending the message, he tells Bob the rule. But Bob is a little clumsy. He doesn’t know how to decode the message.

Now please help Bob to decode the string he received to get the original message.


input

a string which Bob received, including character and number(no space). The number is in [1, 1000]. And the length of the string is less than 100.

output

the original string

Note: The number N in the string may be too big, which makes the output too long. So before output, if N > 7, you need to let N = N % 7 + 1


sample input

a3.3kil2me.h3!23

sample output

aaa…killme.hhh!!!
(23 % 7 + 1 = 3, so we just output three ‘!’)


膜拜TA的标答:

#include 
#include 
#include 

int getNumber(int digit[], int len) {
    int i, p = 1, result = 0;
    for (i = len-1; i >= 0; --i) {
        result += digit[i] * p;
        p *= 10;
    }
    return result;
}

int main() {
    char str[101];
    int digit[10], num;
    int i = 0, j = 0, k = 0;
    scanf("%s", str);
    for (i = 0; i < strlen(str); ++i) {
        if (!isdigit(str[i+1])) {
            printf("%c", str[i]);
        } else {
            k = 0;
            for (j = i+1; j < strlen(str) && isdigit(str[j]); ++j) {
                digit[k++] = str[j] - '0';
            }
            num = getNumber(digit, k);
            if (num > 7) num = num % 7 + 1;
            for (j = 0; j < num; ++j) {
                printf("%c", str[i]);
            }
            i += k;
        }
    }
    printf("\n");
    return 0;
}

我的代码
sscanf函数,在stdio.h里, 可以在字符串里,像scanf那样读取数据。
sscanf

#include 
#include 
#include 

int count_digit(int x)
{
    double ans=log10(x)+1;
    return (int)ans;
}
int main()
{
    char inp[1000];
    scanf("%s",inp);
    int i=0;
    int len=strlen(inp);
    while (ichar ch=inp[i];
        int n;
        if (!(inp[i+1]>='0'&&inp[i+1]<='9'))
        {
            printf("%c",ch);
            i++;
            continue;
        }
        sscanf(inp+i+1,"%d",&n);
        i+=1+count_digit(n);
        if (n>7) n=n%7+1;
        for (int ni=1;ni<=n;ni++) printf("%c",ch);
    }
    printf("\n");
}

你可能感兴趣的:(【大风】【Decode the string】代码分享:sscanf函数)