Strings in c
String variable are used to store a series of character.
Syntax:-
Char str1[10]
String Input/Output Operation
gets() function
The gets() function is simplest method of accepting a string through standard input
Syntax:-
gets(str)
puts() function
The gets() function is used to display a string on standard output device
Syntax:-
puts(str)
Example:-
#include<stdio.h>
#include<conio.h>
void main()
{
char name[10];
clrscr();
puts("Enter name=");
gets(name);
puts(name);
getch();
}
#include<conio.h>
void main()
{
char name[10];
clrscr();
puts("Enter name=");
gets(name);
puts(name);
getch();
}
Strings Function
The strcat() function
The strcat() function is used to join two string values into one.
Syntax:-
strcat(str1,str2)
Example:-
#include<stdio.h>
#include<conio.h>
void main()
{
char fname[10],lname[10];
clrscr();
puts("Enter first name=");
gets(fname);
puts("Enter last name=");
gets(lname);
strcat(lname,fname);
puts(fname);
puts(lname);
getch();
}
#include<conio.h>
void main()
{
char fname[10],lname[10];
clrscr();
puts("Enter first name=");
gets(fname);
puts("Enter last name=");
gets(lname);
strcat(lname,fname);
puts(fname);
puts(lname);
getch();
}
The strcmp() function
The equality (or inequality) of two numbers can be verified using relational operators.The function strcmp()
compares two strings and returns an integer value based on the results of the comparison.
Syntax:-
strcmp(str1,str2)
Example:-
#include<stdio.h>
#include<conio.h>
void main()
{
char fname[10],lname[10];
int n;
clrscr();
puts("Enter first name=");
gets(fname);
puts("Enter last name=");
gets(lname);
n=strcmp(fname,lname);
printf("%d",n);
getch();
}
#include<conio.h>
void main()
{
char fname[10],lname[10];
int n;
clrscr();
puts("Enter first name=");
gets(fname);
puts("Enter last name=");
gets(lname);
n=strcmp(fname,lname);
printf("%d",n);
getch();
}
The strchr() function
The strchr() function determines the occurences of a character in a string.
Syntax:-
strchr(str,ch)
#include<stdio.h>
#include<conio.h>
void main()
{
char name[10],*p,ch='a';
clrscr();
puts("Enter name=");
gets(name);
p=strchr(name,ch);
printf("%s",p);
getch();
}
#include<conio.h>
void main()
{
char name[10],*p,ch='a';
clrscr();
puts("Enter name=");
gets(name);
p=strchr(name,ch);
printf("%s",p);
getch();
}
The strcpy() function
The assignment of one string value to another requires the use of the function strcpy().
Syntax:-
strcpy(str1,str2)
#include<stdio.h>
#include<conio.h>
void main()
{
char fname[10],lname[10];
clrscr();
puts("Enter first name=");
gets(fname);
puts("Enter last name=");
gets(lname);
strcpy(fname,lname);
getch();
}
#include<conio.h>
void main()
{
char fname[10],lname[10];
clrscr();
puts("Enter first name=");
gets(fname);
puts("Enter last name=");
gets(lname);
strcpy(fname,lname);
getch();
}
The strlen() function
The strlen() function returns the length of a string.
Syntax:-
strlen(str)