2013-05-04 87 views
-3

我想更改特定字符串中的數字。例如,如果我有字符串「GenLabel2」,我想將其更改爲「GenLabel0」。我正在尋找的解決方案不僅僅是將字符從2更改爲0,而是使用算術方法。如何使用sprintf更改字符串中的數字?

+0

你是什麼意思的「算術方法」?你能提供一個示例轉換嗎? – 2013-05-04 23:20:22

+0

沿着這些線: char * label =「genLabel2」; char * label2 = label [7] -2;因此,Label2現在是「genLabel0」 – user1819301 2013-05-04 23:21:13

+0

沒關係我使用類似於上面的方法得到它,但我仍然想知道其他方法。 – user1819301 2013-05-04 23:26:53

回答

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; 
}