Reports and tables need text in neat columns, and programs often handle many strings at once, such as a list of names. This section covers the printf options for strings and the two-dimensional character array used to hold several strings.
Width and precision with %s
Syntax
%[-][width][.precision]s
Part
Meaning
width
Minimum number of character positions used; shorter text is padded with spaces
-
Left-justify within the width (the default is right-justified)
.precision
Maximum number of characters printed from the string
*
Take the width or precision from an int argument
With char s[] = "PROGRAMMING"; (square brackets added to show the field edges):
Statement
Output
printf("[%s]", s);
[PROGRAMMING]
printf("[%15s]", s);
[ PROGRAMMING]
printf("[%-15s]", s);
[PROGRAMMING ]
printf("[%.5s]", s);
[PROGR]
printf("[%15.5s]", s);
[ PROGR]
printf("[%-15.5s]", s);
[PROGR ]
Arrays of strings
An array of strings is a two-dimensional char array: the first size is the number of strings, the second is the maximum length of each string including its '\0'.
names[i] (one subscript) is the whole i-th string and can be used with %s; names[i][j] (two subscripts) is a single character.
Key takeaways
Width sets the minimum field size; precision sets the maximum characters printed; - left-justifies.
* takes the width or precision from an argument.
An array of strings is a 2D char array: rows are strings, columns are characters.
names[i] is a string; names[i][j] is a character.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write the statement that prints only the first 4 characters of char city[] = "Chandigarh"; right-justified in a field of 10, and show the output using · for spaces.
Show worked answer
printf("%10.4s", city);. The precision .4 selects “Chan”, and the width 10 pads on the left with 10 − 4 = 6 spaces, so the output is ······Chan.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/arrays-and-strings/formatting-strings-and-arrays-of-strings/ to read this page.