c/c++语言开发共享C – 增加char中的数字

是否可以在字符串中单独增加数字? 所以我要说:

char someString = "A0001"; 

有没有办法增加数字’0001’? 使其成为A0002,A0003等?

     #include  #include  #include  #include  char *strinc(const char *str, int d, int min_width){ char wk[12];//12:max length of sizeof(int)=4 char *p; int len, d_len, c; c = len = strlen(str); while(isdigit(str[--c])); ++c; d += strtol(&str[c], NULL, 10); if(d<0) d = 0; d_len = sprintf(wk, "%0*d", min_width, d); p = malloc((c+d_len+1)*sizeof(char)); strncpy(p, str, c); p[c]=''; return strcat(p, wk); } int main(void){ char *someString = "A0001"; char *label_x2, *label_x3; label_x2 = strinc(someString, +1, 4); printf("%sn", label_x2);//A0002 label_x3 = strinc(label_x2, +1, 4); printf("%sn", label_x3);//A0003 free(label_x2); label_x2 = strinc("A0008", +5, 4); printf("%sn", label_x2);//A0013 free(label_x3); label_x3 = strinc(label_x2, -8, 4); printf("%sn", label_x3);//A0005 free(label_x2); free(label_x3); return 0; } 

    不,你不能这样做,因为它是一个常数

    简单的答案是,没有“简单”的方法来做你所要求的。 您必须解析字符串,提取数字部分并解析为数字。 增加数字,然后将该数字打印回字符串。

    您可以尝试以下简单的示例来基于…编辑:只需阅读BLUEPIXY的答案…他提供了一个很好的function,它将为您做到,返回一个新的字符串,其没有宽度限制我的简单答案……

    有一点值得注意……

    现在代码……

     #include  #include  #include  #include  #ifdef WIN32 #define snprintf sprintf_s #endif int main(int argc, char* argv[]) { /* Assume that the string format is letters followed by numbers */ /* Note use someString[] and NOT someString* */ char someString[] = "A0001"; char *start = someString; char *end = start + strlen(someString); /* End points to the NULL terminator */ char *endOfParse; char c; unsigned long num; ptrdiff_t numDigits; /* Find first numeric value (start will point to first numeric * value or NULL if none found */ while( true ) { c = *start; if( c == '' || isdigit(c) ) break; ++start; } if( c == '' ) { printf("Error: didn't find any numerical charactersn"); exit(EXIT_FAILURE); } /* Parse the number pointed to by "start" */ num = strtoul(start, &endOfParse, 0); if(endOfParse < end ) { printf("Error: Failed to parse the numerical portion of the stringn"); exit(EXIT_FAILURE); } /* Figure out how many digits we parsed, so that we can be sure * not to overflow the buffer when writing in the new number */ numDigits = end - start; num = num + 1; snprintf(start, numDigits+1, "%0*u", numDigits, num); /* numDigits+1 for buffer size to include the null terminator */ printf("Result is %sn", someString); return EXIT_SUCCESS; } 

    你不能仅仅因为它不像你看起来那么简单。 你需要先了解很多关于你想要做什么的事情。 例如,您将字符串的哪一部分作为要递增的数字?

    当您有所有这些问题的答案时,您可以在函数中实现它们。 之后的许多可能方法之一可以是创建一个新的子字符串,它将表示要递增的数字(此子字符串将从someString中取出)。 然后使用atoi()将该字符串转换为数字,递增数字并将此递增的数字替换为someString中的字符串。(someString需要为String或char * btw)。

      以上就是c/c++开发分享C – 增加char中的数字相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/519683.html

      (0)
      上一篇 2020年12月5日
      下一篇 2020年12月5日

      精彩推荐