Character sequences (String)

It is a sequence of characters that are treated as a single data item. Any collection of characters defined between double quotation marks is a string constant. For example:-

“Hello Paul”; “London”;
C does not support string as a data type. However, it allows us to represent strings as character arrays. So, A general form of declaration of string or character array is:-

char string_name[Size};
* When the compiler assigns a character string to a character array, it automatically enters a ‘null character’ at the end of the character array.

Initializing character Array

Like integer array, character array may be initialized when they are declared. Character arrays to be initialized in either of the following forms:-

char a[6]=”Hello”; char a[6]={‘H’,’e’,’l’,’l’,’o’} or char a[6]={‘H’,’e’,’l’,’l’,’o’,’\0′}
In this case, the compiler creates a character array of size 6, Places the value “hello” in it, terminates with a null character. The storage will look like:-

string in c programming [H][e][l][l][o][/n]

C Code Example

Reading Strings From Terminal

Using Scanf()

scanf cann be used with %s format specifier to read in a string of characters.For example:-

char name[10]; scanf(“%s”, name);
*The problem with the scanf function is that it terminates its input on the first white space it finds.

Using getchar

We know that getchar is used to read-only a single character from the input but with help of a loop, we can able to repeatedly read a successive single characters from input and place them into a character array. For example:-

Note:-getchar has no arguments

C Code Example

Using gets

Reading a string of text containing whitespaces is to use the library function gets available in the <stdio.h> header file.It read character from the keyboard until the new-line character is encountered and then it automatically enters null character at the end. A general form is:-

char string[10]; gets(string);

C Code Example

Writing Strings From Terminal

Using printf()

We have already use the printf function in our previous example. The format %s can be used to display an array of characters that is terminated by the null character. For example:-

printf(“%s”,array_name);

Using putchar

Like getchar, C supports another character handling function putchar for the output purpose but it is used to write only a single character to the output. A general form of putchar is:-

char string=’L’; putchar(string);
Note:-It require only one parameter which refer to arrays or string.

we can able to write successive single characters to the output screen with help of a loop. For example:-

C Code Example

Using puts

Another way of printing string is to use puts which are declared in <stdio.h>.Like gets it also has one parameter. A general form of puts is:-

char string[6]=”hello”; puts(string);

C Code Example