Working with Strings & Standard Functions 245
Table 8.2 String formats with different precision
Sr. No. Statement Output
1.
printf ("%sn", text);
PRABHAKAR
2.
printf ("%. 5s
", text);
PRABHA
3. printf ("%.8s
",te xt); PRABHAKA
4. printf ("%. 15sn", text); PRABHAKAR
5. Printf (u%-10.4sn",text);
PRAB
6.
Printf (m i s " , text) ;
PRABHAKAR
Where, the te x t is ' PRABHAKAR'
1) The 1st statement displays the output ' PRABHAKAR'. The entire string can be displayed with
the first statement.
2) We can also specify the precision with character string, which is to be displayed. The precision
is (number of characters to be displayed-) provided after decimal point. For instance in the 2nd
statement in the above table the first five characters are displayed. Here the integer value 5 on
the right side of the decimal point, which specifies the five characters to be displayed.
3) In 3rd statement first eight characters are displayed.
4) While statement number four -displays the entire strings.
5) The 5th statement with -sign (Ex. %-10.4s ), displays the string with left justified.
6) When the field length is less than the length of the string the entire string is printed. When it is
greater than the length of the string, blank spaces are initially printed followed by the string.
This effect can be seen in the 6th statement.
7) When number of characters to be displayed is specified as zero after decimal point nothing
will be displayed.
Few examples are illustrated below giving the effects of various formats of strings.
8.4 Write a program to display the string 'PRABHAKAR' using various format specifications.
mainO
{
char t e x t [1 5 ]-"PRABHAKAR';
c lr s c r O ;
printf ("% s n",tex t);
printf ("% .5sn",text);
printf ( “% .8s
", text);
printf ("% .15sn ",text);
Printf C%-10.4s”,text);
Printf ("% lls",te x t);
)
OUTPUT:
PRABHAKAR
PRABH