How do you print only part of a string?


The following program shows how to print only part of a string using the printf() function:

#include <stdio.h>
#include <string.h>
void main(void);
void main(void)
     char* source_str = "THIS IS THE SOURCE STRING";
     /* Use printf() to print the first 11 characters of source_str. */
     printf("First 11 characters: '%11.11s'\n", source_str);
     /* Use printf() to print only the
        last 13 characters of source_str. */
     printf("Last 13 characters: '%13.13s'\n",
                 source_str + (strlen(source_str) - 13));

This example program produces the following output:

First 11 characters: 'THIS IS THE'

Last 13 characters: 'SOURCE STRING'

The first call to printf() uses the argument "%11.11s" to force the printf() function to make the output exactly 11 characters long. Because the source string is longer than 11 characters, it is truncated, and only the first 11 characters are printed. The second call to printf() is a bit more tricky. The total length of thesource_str string is calculated (using the strlen() function). Then, 13 (the number of characters you want to print) is subtracted from the total length of source_str.

This gives the number of remaining characters in source_str. This number is then added to the address of source_str to give a pointer to an address in the source string that is 13 characters from the end of source_str. By using the argument "%13.13s", the program forces the output to be exactly 13 characters long, and thus the last 13 characters of the string are printed.


© 2017