2017年1月23日 星期一

[C] Return index of last non digit or -1 if it does not end with digits

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

/* return index of last non digit or -1 if it does not end with digits */
int rindex_nondigit(char *name)
{
    int pos = 0;

    for(pos=strlen(name); pos>0; pos--)
    {
        printf("pos = %d, name[pos - 1] = %c \n", pos, name[pos-1]);
        if (!isdigit(name[pos-1]))
            return pos;
    }
    return 0;
}


int main()
{
    int position = 0;
    char a[] = "happy1";

    position = rindex_nondigit(a);
    printf("position = %d\n", position);
}



Result

pos = 6, name[pos - 1] = 1 
pos = 5, name[pos - 1] = y 
position = 5



Reference:

0 意見:

張貼留言