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?
You can use strncpy to duplicate the part of your string you want to print, but you'd have to take care to add a null terminator, as strncpy won't do that if it doesn't encounter one in the source string.
%c deals with a char (that is, a single character), whereas %s deals with a char * (that is, a pointer to an array of characters, hopefully null-terminated).
%s tells printf that the corresponding argument is to be treated as a string (in C terms, a 0-terminated sequence of char ); the type of the corresponding argument must be char * . %d tells printf that the corresponding argument is to be treated as an integer value; the type of the corresponding argument must be int .
So it turns out that, in C, it's actually impossible to write a proper "utility" substring function, that doesn't do any dynamic memory allocation, and that doesn't modify the original string. All of this is a consequence of the fact that C does not have a first-class string type.
Try this:
int length = 5;
printf("%*.*s", length, length, "hello there");
This will work too:
fwrite(str, 1, len, stdout);
It will not have the overhead of parsing the format specifier. Obviously, to adjust the beginning of the substring, you can simply add the index to the pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With