Saving a string until a last delimiter is found - C

1.4k views Asked by At

Is it possible to use strtok or some other string function to cut the string until the point where last delimiter is found.

Specific example would be date; I would like to transform "4.1.2017." to "4.1.2017" - without the dot at the end.

2

There are 2 answers

0
Sergey Kalinichenko On

If you have a single delimiter, use strrchr to find its last occurrence in the string:

char str[] = "quick.brown.fox";
char *ptr = strrchr(str, '.');
if (ptr) {
    *ptr = '\0';
}
printf("%s\n"' str);

This produces the following output:

quick.brown
0
Michi On

Like I explained in My comment (if you don't want to use strrchr or you cannot for some reasons) I'll create a Function which checks the position of that delimiter like this:

int my_strrchr(const char *ptr, const char delimiter){
    if (ptr == NULL ){
        printf("Error, NULL Pointer\n");
        return -1;
    }

    if ( *ptr == '\0' ){
        printf("Error, the Buffer is Empty\n");
        return 0;
    }

    int i = 0;
    int ret = 0;

    while( ptr[i] != '\0' ){
        if ( ptr[i] == delimiter ){
            ret = i;
        }
        i++;
    }

    return ret;
}

And use it Like this:

#include <stdio.h>

int main(void){
    char arr[] = "4.1.2017.";
    char delimiter = '.';

    int len;

    if( (len = my_strrchr(arr, delimiter)) > 0){
        while ( arr[len] != '\0'){
            arr[len] = '\0';
        }
        printf("%s\n", arr);
    }
}

See DEMO. Any way this is only to get you an Idea and as you can see I use no standard Functions here.