C: Strings/Char Arrays

In C, strings are represented as arrays of characters, each terminated by the escape sequence '\0', known as the null character. Therefore, a string variable in C is always declared as a character array. For example, this is how we declare a string variable called city of 9 characters


char city[9];

Initializing a string variable to some string constant/literal consisting of N characters require specifying the array to be of at least N+1 characters, adding one extra for the null character. Consider the string literal "SHILLONG", which consists of 8 characters. The character array city need to be of at least 8+1 (= 9) characters to hold it


char city[9] = "SHILLONG";

The other way to initialize it is as


char city[9] = {'S','H','I','L','L','O','N','G','\0'};

with the null character '\0' marking its end.

We can also initialize a character array without specifying the number of elements as


char city[] = "SHILLONG";

or


char city[] = {'S','H','I','L','L','O','N','G','\0'};

Printing Strings

The printf() function with its %s format specifier is used for printing strings


char city[] = "SHILLONG";
printf("%s", city);

The puts() function can also be used for the same


char city[] = "SHILLONG";
puts(city);

Reading Strings from Input/Keyboard

The scanf() function's %s format specifier can be used for reading strings without whitespace


char city[9];
scanf("%s", city);

However, the reading stops on encounter of the first whitespace like a blank/space. For example, if the city "Sao Luis" is being entered, it would terminate on encountering the first space after "Sao" while typing. To read such strings with whitespaces, we can use the conversion specifier %[^\n] as shown below


char city[9];
scanf("%[^\n]", city);

getchar()

Though meant for reading a single character from the terminal, the getchar() function can also be used for reading strings, even with whitespaces

	
#include <stdio.h>

main() {	
	char city[9], ch;	
	unsigned n = 0;	

	printf("city:");

	do {
		ch = getchar();
		city[n] = ch;
		n++;
	} while(ch != '\n');

	printf("%s", city);	
}

You can increase the character array city to beyond 9 characters to enter longer city names like "Rio de Janeiro."

Notes

  • The gets() function is not explored here as it is already deprecated.