Strings in c language with examples

Preview
You must first complete Display output in C – printf() function before viewing this Lesson

Strings in c language with examples

String is group of one or more characters within double quotes (“).

Example:  “Lovejot” , “2019” , “Rs4000”,  “ladderpython@gmail.com” 


1. String variable?

An array of char type is known as a string variable.

Example: char sname[20];

In this example, sname is a string variable which can contain maximum 19 characters.



2. Initialization of a string variable

There are two ways to initialize a string varible:

a. The first way to initialize a string variable is

char var_name[Size]={List of characters};

Example

char studentname[5]={‘A’,’m’,’i’,’t’};

In examples above, string variable studentname has been initialized with the value “Amit”.

b. The second way to initialize a string variable is

char var_name[Size]=”Value”;

Example         

char studentname[5]=”Amit”;

Program to initialize a string variable.
#include<stdio.h>
int main()
{
char studentname[]=” Amita”;

//char studentname1[]={‘A’,’m’,’i’,’t’,’a’};
printf(“\nname=%s”,studentname);
return(0);
}

Output
name=Amita



3. Reading and displaying a string variable

We can read and display a string variable just as we read a normal variable of C Language.

Program to read and display a string variable.
#include<stdio.h>
int main()
{
char studentname[20];
printf(“Enter name of student=”);
gets(studentname);
printf(“\nStudentname=%s”,studentname);
return(0);
}




Lesson tags: display string in c, initialicze a string variable in, read string value in c, string in c
Back to: C Programming Language