C Programming String
C Programming String
In C programming, array of character are called strings. A string is terminated by null character /0 . For
example:
"c string tutorial"
Here, "c string tutorial" is a string. When, compiler encounters strings, it appends null character at the end of
string.
Declaration of strings
Strings are declared in C in similar manner as arrays. Only difference is that, strings are of char type.
char s[5];
Initialization of strings
In C, string can be initialized in different number of ways.
char c[]="abcd";
OR,
char c[5]="abcd";
OR,
char c[]={'a','b','c','d','\0'};
OR;
char c[5]={'a','b','c','d','\0'};
String variable c can only take a word. It is beacause when white space is encountered, the scanf() function
terminates.
Write a C program to illustrate how to read string from terminal.
#include <stdio.h>
int main(){
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s.",name);
return 0;
}
Output
Enter name: Dennis Ritchie
Your name is Dennis.
Here, program will ignore Ritchie because, scanf() function takes only string before the white space.
This process to take string is tedious. There are predefined functions gets() and puts in C language to read
and display string respectively.
int main(){
char name[30];
printf("Enter name: ");
gets(name);
//Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}
Output
Enter name: Tom Hanks
Name: Tom Hanks