Search code examples
cprintfsubstringc-stringsfunction-definition

Print (work with) substrings in a C program


How do I work with a string if I only want to print part of it?

For example, print "bcd" from "abcdef"?

I know how to work with a pointer to the beginning of a string, but I don't know how to determine the end.

void vypis(char *retezec)
{   
    printf("%s", retezec);
}

int main (void)
{
    char *str = NULL;
    size_t capacity;
        
    getline(&str, &capacity, stdin);    
    vypis(str);
    vypis(str+1);       
}

Solution

  • I know how to work with a pointer to the beginning of a string, but I don't know how to determine the end.

    A pointer to the last character you'd like to print is a possible solution:

    void vypis(const char *retezec, const char *end)
    {   
        while (retezec <= end && *retezec != '\0')
        {
            putchar(*retezec);
            retezec++;
        }
        putchar('\n');
    }
    
    int main (void)
    {
        char *str = NULL;
        size_t capacity = 0;
            
        getline(&str, &capacity, stdin);    
        vypis(str, str + 5);      //prints from str[0] to str[5]
        vypis(str + 1, str + 3);  //prints from str[1] to str[3]     
    }