如何使用sprintf更改字符串中的数字?

时间:2013-05-04 23:17:25

标签: c string printf

我想更改特定字符串中的数字。例如,如果我有字符串“GenLabel2”,我想将其更改为“GenLabel0”。我正在寻找的解决方案不仅仅是将字符从2更改为0,而是使用算术方法。

1 个答案:

答案 0 :(得分:1)

此方法适用于大于9的数字。它取字符串中最右边的数字,并向其添加任意数字(从命令行读入)。字符串中的数字被假定为正数。

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

#define LABEL_MAX 4096

char *find_last_num(char *str, size_t size)
{
    char *num_start = (char *)NULL;
    char *s;

    /* find the start of the last group of numbers */
    for (s = str + size - 1; s != str; --s)
    {
        if (isdigit(*s))
            num_start = s;
        else if (num_start)
            break; /* we found the entire number */
    }
    return num_start;
}

int main(int argc, char *argv[])
{
    char label[LABEL_MAX] = "GenLabel2";
    size_t label_size;
    int delta_num;
    char *num_start;
    int num;
    char s_num[LABEL_MAX];

    /* check args */
    if (argc < 2)
    {
        printf("Usage: %s delta_num\n", argv[0]);
        return 0;
    }
    delta_num = atoi(argv[1]);

    /* find the number */
    label_size = strlen(label);
    num_start = find_last_num(label, label_size);

    /* handle case where no number is found */
    if (!num_start)
    {
        printf("No number found!\n");
        return 1;
    }

    num = atoi(num_start);     /* get num from string */
    *num_start = '\0';         /* trim num off of string */
    num += delta_num;          /* change num using cl args */
    sprintf(s_num, "%d", num); /* convert num to string */
    strncat(label, s_num, LABEL_MAX - label_size - 1); /* append num back to string */
    label[LABEL_MAX - 1] = '\0';
    printf("%s\n", label);

    return 0;
}