[Solved] Get substring of argv[0] between n and the length of argv


Here is a program with comments explaining how you can do what you want. Hopefully it will help you learn how to solve such problems.

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

/* Use if strdup() is unavailable.  Caller must free the memory returned. */
char *dup_str(const char *s)
{
    size_t n = strlen(s) + 1;
    char *r;
    if ((r = malloc(n)) == NULL) {
        return NULL;
    }
    strcpy(r, s);
    return r;
}

/* Use if POSIX basename() is unavailable */
char *base_name(char *s)
{
    char *start;

    /* Find the last "https://stackoverflow.com/", and move past it if there is one.  Otherwise return
       a copy of the whole string. */
    /* strrchr() finds the last place where the given character is in a given
       string.  Returns NULL if not found. */
    if ((start = strrchr(s, "https://stackoverflow.com/")) == NULL) {
        start = s;
    } else {
        ++start;
    }
    /* If you don't want to do anything interesting with the returned value,
       i.e., if you just want to print it for example, you can just return
       'start' here (and then you don't need dup_str(), or to free
       the result). */
    return dup_str(start);
}

/* test */
int main(int argc, char *argv[])
{
    char *b = base_name(argv[0]);

    if (b) {
        printf("%s\n", b);
    }
    /* Don't free if you removed dup_str() call above */
    free(b);

    return EXIT_SUCCESS;
}

3

solved Get substring of argv[0] between n and the length of argv