It is a collection of characters (single alphabet, number, punctuation mark or other symbol) enclosed within a pair of double quotes.
String Syntax
char [size];
Strings Initialization
Giving value to a sting is called as String Initialization.
Example
char str[16]=”wisdom materials”;
char str[16]={ ‘w’, ’i’, ’s’, ‘d ’,’ o’, ’m’,’ ’,’m’, ’a’, ’t’, ’e’ ,’r’ ,’i’ ,’a’ ,’l’ ,’s’,’\0’};
Reading and Writing strings
Operations on String
|
Functions Used
|
Reading strings
|
Scanf, gets
|
Writing strings
|
Printf,puts
|
Sample Programs
Program to read and print strings.
|
Output
|
#include <stdio.h>
void main ()
{
char str[50];
puts("Enter a String");
gets(str);
puts("Entered a String");
puts(str);
}
|
Enter a String
WisdomMaterials.com
Entered a String
WisdomMaterials.com
|
#include <stdio.h>
void main ()
{
char str[50];
printf("Enter a String\n");
scanf("%s",str);
printf("Entered a String\n");
printf(str);
}
|
Enter a String
WisdomMaterials.com
Entered a String
WisdomMaterials.com
|
Program find String length
|
Output
|
#include<stdio.h>
void main()
{
char str[]="wisdom materilas",ch;
int len=0,i=0;
while( str[i]!='\0')
{i++;
len ++;
}
printf("\n string length= %d",len);
}
|
string length=16
|
Program for
concatenate two strings
|
Output
|
#include<stdio.h>
void main()
{
char str1[40]="wisdom";
char str2[12]="materials";
int i=0,j=0;
while( str1[i]!='\0')
i++;
while( str2[j]!='\0')
{
str1[i]=str2[j];
i++;
j++;
}
str1[i]=NULL;
printf("\n First string after concatenations =
%s",str1);
}
|
First string after concatenations is wisdommaterials
|
Program to
copying 1 string to other string
|
Output
|
#include<stdio.h>
void main()
{
char str1[20]="wisdom";
char str2[20]="materials";
char ch;
int i;
for(i=0;str2[i]!='\0';i++)
str1[i]=str2[i];
str2[i]='\0';
printf("\n str1 = %s",str1);
}
|
string 1 is materials
|
Program for strings Comparison
|
Output
|
#include<stdio.h>
void main()
{
char str1[20]="wisdom";
char str2[20]="materials";
int i,diff=0;
for(i=0;str1[i]!='\0'||str2[i]!='\0';i++)
if(str1[i]==str2[i])
continue;
else
{
diff=str1[i]-str2[i];
break;
}
if(diff>0)
printf("str1 is greater");
else if (diff<0)
printf("str1 is smaller");
else printf("both are same");
}
|
str1 is greater
|
Program for Extraction of a substring
|
Output
|
#include<stdio.h>
void main()
{
char str1[25]="Wisdom materials";
char substr[25];
int i,j;
//start=3;length=5;
for(i=5,j=0;j<10;i++,j++)
substr[j]=str1[i];
substr[j]='\0';
printf("\n substr : %s",substr);
}
|
substr : m material
|
|