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:-
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:-
C Code Example
1 2 3 4 5 6 7 |
#include <stdio.h> void main() { char name[15]; scanf("%s", name); printf("www.%s.in",name); } |
Reading Strings From Terminal
Using Scanf()
scanf cann be used with %s format specifier to read in a string of characters.For example:-
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <stdio.h> void main() { char string[10],ch; int i=0; printf("Enter element "); do { ch = getchar(); string[i]=ch; i++; }while(ch != '\n'); printf("\n %s",string); } |
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:-
C Code Example
1 2 3 4 5 6 7 8 |
#include <stdio.h> void main() { char string[10]; printf("Enter element x "); gets(string); printf("\n %s",string); } |
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:-
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:-
we can able to write successive single characters to the output screen with help of a loop. For example:-
C Code Example
1 2 3 4 5 6 7 8 9 10 11 |
#include <stdio.h> void main() { char string[6]="hello"; int i=0; do { putchar(string[i]); i++; } while(i != 6); } |
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:-
C Code Example
1 2 3 4 5 6 7 8 |
#include <stdio.h> void main() { char string[10]; printf("Enter element :- "); gets(string); puts(string); } |