You can use printf()
:
#include <stdio.h>
int main (void)
{
char *str = "0123456789";
printf("%.6s\n", str + 1);
return 0;
}
The precision in the %s
conversion specifier specifies the maximum number of characters to print. You can use a variable to specify the precision at runtime as well:
#include <stdio.h>
int main (void)
{
int length = 6;
char *str = "0123456789";
printf("%.*s\n", length, str + 1);
return 0;
}
In this example, the * is used to indicate that the next argument (length
) will contain the precision for the %s conversion, the corresponding argument must be an int
.
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:
#include <stdio.h>
int main (void)
{
int length = 10;
char *str = "0123456789";
printf("%.*s\n", length, str + 5);
return 0;
}
Will print "56789
". If you always want to print a certain number of characters, specify both a minimum field width and a precision:
printf("%10.10s\n", str + 5);
or
printf("%*.*s\n", length, length, str + 5);
which will print:
" 56789"
You can use the minus sign to left-justify the output in the field:
printf("%-10.10s\n", str + 5);
Finally, the minimum field width and the precision can be different, i.e.
printf("%8.5s\n", str);
will print at most 5 characters right-justified in an 8 character field.