-3

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

4

1 回答 1

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;
}
于 2013-05-05T00:59:17.557 回答