Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

printf - 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);       
}
question from:https://stackoverflow.com/questions/65935653/print-work-with-substrings-in-a-c-program

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 != '')
    {
        putchar(*retezec);
        retezec++;
    }
    putchar('
');
}

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]     
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...