2 - String
2 - String
Chapter No: 2
Chapter Name: Strings
String:
A String in C is nothing but a collection of characters.
In C, Strings is represented by arrays of characters.
Strings are always ended with null character (‘\0’).
Strings are always enclosed by double quotes. Whereas, character is enclosed by
single quotes in C.
When we define a string as char s[10], the character s[10] is implicitly initialized
with the null in the memory.
Syntax:
char s[5];
or
char s[]=”VPCSC”;
or
char s[]={‘V’,’P’,’C’,’S’,’C’,’\0’};
V P C S C \0
Example :
Input Output
#include <stdio.h>
void main() Enter String : VPCSC
{ String = VPCSC
char s[10];
printf("Enter String : ");
gets(s);
printf("String = %s",s);
}
String Functions:
Input Output
1. strlen
2. strrev
#include <stdio.h>
#include <string.h> Enter String : vpcsc
void main()
Reverse of String = cscpv
{
char s[10];
printf("Enter String : ");
gets(s);
printf("Reverse of String = %s",strrev(s));
}
3. strlwr()
4. strupr()
char s1[10],s2[10];
printf("Enter String : ");
gets(s2);
strcpy(s1,s2);
printf("S1 = %s\nS2 = %s",s1,s2);
}
6. strcat()
7. strcmp()
char s1[10],s2[10];
printf("Enter First String : ");
gets(s1);
printf("Enter Second String : ");
gets(s2);
if((strcmp(s1,s2))==0)
printf("Both Strings are Equal");
else
printf("Both Strings are Not Equal");
}
String Programs
Input Output
#include<stdio.h>
Enter String : indapur
#include<string.h>
void main() iau
{
Total Vowels = 3
char s[10];
int i,cnt=0;
printf("Enter String : ");
gets(s);
for(i=0;i<strlen(s);i++)
{
if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u')
{
cnt++;
printf("%c",s[i]);
}
}
printf("\nTotal Vowels = %d",cnt);
}
Q. Write a C Program to print string pattern.
#include<stdio.h>
#include<string.h> Enter String : vpcsc
void main()
v
{
v p
char s[10];
v p c
int i,j;
v p c s
printf("Enter String : "); v p c s c
gets(s);
for(i=0;i<strlen(s);i++)
{
for(j=0;j<=i;j++)
printf(" %c ",s[j]);
printf("\n");
}
}
#include<stdio.h>
#include<string.h> Enter Five Strings :
#include<conio.h> VPCSC
void main() TC
{ SP
char s[5][10]; VPP
int i; JSPM
clrscr(); Accepted Strings :
printf("Enter Five Strings : \n"); VPCSC
for(i=0;i<5;i++) TC
gets(s[i]); SP
printf("Accepted Strings : \n"); VPP
for(i=0;i<5;i++) JSPM
puts(s[i]);
}