Let’s say I have a char* str = '0123456789' and I want to cut the first and the last three letters and print just the middle, what is the simplest, and safest, way of doing it?
Now the trick: The portion to cut and the portion to print are of variable size, so I could have a very long char*, or a very small one.
You can use
printf(), and a special format string:The precision in the
%sconversion specifier specifies the maximum number of characters to print. You can use a variable to specify the precision at runtime as well:In this example, the * is used to indicate that the next argument (
length) will contain the precision for the%sconversion, the corresponding argument must be anint.Pointer arithmetic can be used to specify the starting position as I did above.
[EDIT]
One more point, if your string is shorter than your precision specifier, less characters will be printed, for example:
Will print ‘
56789‘. If you always want to print a certain number of characters, specify both a minimum field width and a precision:or
which will print:
You can use the minus sign to left-justify the output in the field:
Finally, the minimum field width and the precision can be different, i.e.
will print at most 5 characters right-justified in an 8 character field.