Print part of a string in C

Mark picture Mark · Jan 30, 2011 · Viewed 32.1k times · Source

Is there a way to only print part of a string?

For example, if I have

char *str = "hello there";

Is there a way to just print "hello", keeping in mind that the substring I want to print is variable length, not always 5 chars?

I know that I could use a for loop and putchar or that I could copy the array and then add a null-terminator but I'm wondering if there's a more elegant way?

Answer

Jerry Coffin picture Jerry Coffin · Jan 30, 2011

Try this:

int length = 5;
printf("%*.*s", length, length, "hello there");