Monday 7 November 2011

How do you print only part of a string? in C programming

How do you print only part of a string?

FAQ VI.6 showed you how to copy only part of a string. But how do you print a portion of a string? The
answer is to use some of the same techniques as in the example for FAQ VI.6, except this time, rather than
the strncpy() function, the printf() function is used. The following program is a modified version of the
example from FAQ VI.6 that 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 the
source_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.

See FAQ VI.6 for a similar example of extracting a portion of a string using the strncpy() function rather
than the printf() function.

Cross Reference:

VI.1: What is the difference between a string copy (st
rcpy) and a memory copy (memcpy)? When
should each be used?
VI.6: How can I copy just a portion of a string?

No comments:

Post a Comment