String is a one dimensional array where we store group of characters. Some time we call it “character array”. Character array or strings are used by programming languages to manipulate text such as words and sentence.
Syntax of declaring a string
Now let’s write a program on it
Let’s write a program on it
There is a way to make “scanf()” accept multi-word string. Let’s write a program
Syntax of declaring a string
char string_name [string_size]
Syntax of initializing a string
char string_name [string_size]=”Your String”
Here “string_size” is the size of maximum character accepted by “string_name”. writing “char” before declaring says it is a string.Now let’s write a program on it
#include<stdio.h>
void main()
{
char name[]="Programs Page";
printf("%s",name);
}
The output of this program will bevoid main()
{
char name[]="Programs Page";
printf("%s",name);
}
Programs Page
Here “%s” is a format specification in “printf()” to print string. We will use same specification for receiving inputs from users.Let’s write a program on it
#include<stdio.h>
void main()
{
char name[30];
printf("Enter String\n");
scanf("%s",name);
printf("\nWelcome %s",name);
}
Above program is a small example of receiving inputs from user.in declaration of “name[30]” sets 30 byte of space for string “name[]”. Output of this program isvoid main()
{
char name[30];
printf("Enter String\n");
scanf("%s",name);
printf("\nWelcome %s",name);
}
Enter String
Programs Page
Welcome Program
Now wait! Where is the string after space? This is a problem because “scanf()” is not capable of receiving multi-word strings. For that string “Programs Page” string become un accepted. Now let’s use “gets()” and “puts()”Programs Page
Welcome Program
#include<stdio.h>
void main()
{
char name[5];
printf("Enter String\n");
gets(name);
puts("Welcome ");
puts(name);
}
Output of this programvoid main()
{
char name[5];
printf("Enter String\n");
gets(name);
puts("Welcome ");
puts(name);
}
Enter String
Programs Page
Welcome
Program Page
“gets()” is use for store the string inside “name” and “puts()” is use for printing. But they have some problem too. “gets()” is capable of receiving one sting at a time and “puts()” can display one string at a time.Programs Page
Welcome
Program Page
There is a way to make “scanf()” accept multi-word string. Let’s write a program
#include<stdio.h>
void main()
{
char name[5];
printf("Enter String\n");
scanf("%[^\n]s",name);
printf("\nWelcome %s",name);
}
Output of this programvoid main()
{
char name[5];
printf("Enter String\n");
scanf("%[^\n]s",name);
printf("\nWelcome %s",name);
}
Enter String
Programs Page
Welcome Program Page
Here, [^\n] indicates that “scanf()” will keep receiving character into “name[]” until you press enter.Programs Page
Welcome Program Page




