C - Increment a number within a char

寵の児 提交于 2019-12-08 11:48:12

问题


Is it possible to increment a number alone within a string? So let's say I have:

char someString = "A0001";

Is there a way to increment the number '0001'? To make it A0002, A0003 etc?


回答1:


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

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]='\0';
    return strcat(p, wk);
}

int main(void){
    char *someString = "A0001";
    char *label_x2, *label_x3;

    label_x2 = strinc(someString, +1, 4);
    printf("%s\n", label_x2);//A0002
    label_x3 = strinc(label_x2, +1, 4);
    printf("%s\n", label_x3);//A0003
    free(label_x2);
    label_x2 = strinc("A0008", +5, 4);
    printf("%s\n", label_x2);//A0013
    free(label_x3);
    label_x3 = strinc(label_x2, -8, 4);
    printf("%s\n", label_x3);//A0005
    free(label_x2);
    free(label_x3);

    return 0;
}



回答2:


no u cannot do it because it is a constant




回答3:


The simple answer is that there is no "easy" way to do what you're asking. You would have to parse the string, extract the numerical portion and parse into a number. Increment the number and then print that number back into your string.

You could try the following simple example to base something on... EDIT: Just read BLUEPIXY's answer... he presents a nice function that will do it for you, return you a new string, which doesn't have the width restriction of my simple answer...

There are some points worth noting...

  1. Use char someString[] = "A0001"; and not char *someString = "A0001";. The reason is that the former allocates memory on the stack for the string, the latter is a pointer to a string in memory. The memory location decided upon by the compiler in the latter case and is not always guaranteed to be writable.
  2. Crappy #define for snprintf on Windows... not sure that's a good thing. The point is really use a safe buffer writing function that won't overflow the bounds of your array.
  3. The snprintf format string "%0*u" Formats an unsigned integer with a minimum width specified by the argument to the left of the actual integer and the zero tells it to left pad with zeros if necessary.
  4. If your number increases to a width greater than, in this case, 4 digits, the buffer won't overflow, but your answers will look wrong (I haven't put in any logic to increment the buffer size)
  5. I am assuming the the format of the string is always a set of non-numerical-digits, followed by a set of numerical digits and then a null terminator.

Now the code...

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

#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 == '\0' || isdigit(c) )
            break;

        ++start;
    }

    if( c == '\0' )
    {
        printf("Error: didn't find any numerical characters\n");
        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 string\n");
        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 %s\n", someString);   

    return EXIT_SUCCESS;
}



回答4:


You can't do it simply because its not as simple to machine as it looks to you. There are a lot of things you need to understand about what you are trying to do first. For example, What part of string are you taking as a number which is to be incremented?

  • Last digit only?
  • A number which will be followed by SINGLE alphabet?
  • A number which may be followed by any number of alphabets?
  • LAST number in a string, for example A33B43 would mean to increment 33 or 43?

When you have answers to all such questions, you can implement them in a function. One of the many possible approaches thereafter can be to make a new substring which will represent the number to be incremented(this substring is to be taken out from your someString). Then use atoi() to convert that string into number, increment the number and replace this incremented number as a string in someString.(someString needs to be String or char * btw).



来源:https://stackoverflow.com/questions/16770040/c-increment-a-number-within-a-char

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!