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

最佳答案

此方法适用于大于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;
}

关于c - 如何使用sprintf更改字符串中的数字?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16379837/

10-11 22:06
查看更多