Header Ads Widget

Reading and writing of string using character array.

 In c programming language provides a separate Access specifier i.e. %S to read and write sequence of characters of a string .

Following is the example of reading sequence  of character using ' %S ' Access specifier.

Example:  Char name [12 ];

Read / Input string:-  

scanf(" %s ",name);

Write / output  string:-  

printf("%s ",name);

The drawback of the %s Access specifier is that it stops reading the input as soon as it encounters a whitespace ( Normal space , Tab space etc. ) 

Note:-  There is another built in function  provide by c which can read the input character sequence that include whitespaces too.   

gets( string_name );

There is also another built in function for printing the string which is puts . by using puts we can easily display the input string .

puts(string_name);

/* Program to find the length of an input string */

Code:-

#include<stdio.h>
int main()
{
char s[]="EasyCodingZone";
int len=0,i;
for(i=0;s[i]!='\0';i++)
{
len++;
}
printf("Length of the string is %d",len);
return 0;
}

Output:-
Length of the string is 14

/*  if string is input through the user  */

#include<stdio.h>
int main()
{
char s[50];
int len=0,i;
printf("Enter the string\n");
scanf("%s",s);
for(i=0;s[i]!='\0';i++)
{
len++;
}
printf("Length of the string is %d",len);
return 0;
}

How to take input of a string which have white spaces:-  Click Here

 There are many way to take input of the string .

2)  scanf("%[^\n]",string_name):-

Code:-

#include<stdio.h>
#include<string.h>
int main()
{
char bin[100];
int word=0;
printf("Enter a sentence\n");
scanf("%[^\n]",bin);
printf("The output is:-\n");
puts(bin);
return 0;
}

Output:-

Enter a sentence
This is EasyCodingZone
The output is:-
This is EasyCodingZone

3) gets(string_name):-

Code:-

#include<stdio.h>
#include<string.h>
int main()
{
char bin[100];
int word=0;
printf("Enter a sentence\n");
gets(bin);
printf("The output is:-\n");
puts(bin);
return 0;
}

Output:-

Enter a sentence
This is EasyCodingZone
The output is:-
This is EasyCodingZone








Recommended Post:

Key points:-

Cracking the coding interview:-

 Array and string:-

Tree and graph:-

Hackerearth Problems:-

Hackerrank Problems:-

Data structure:-

 MCQs:-