C provides large set of string handling library function under string.h header. Few of them are discussed below.
Strlen
This function returns the length of the given string which is an integer value.
Syntax
strlen(name_of_array);
The actual parameter for the function is the address of the first character of the array.
Usage
#include<stdio.h>
#include<string.h>
int main()
{
char name[]="Abhilekh";
printf("length is %d",strlen(name));
return 0;
}
The output is:
The length of the string is 8
Strcpy
It should be noted that a string cannot be assigned to another string using a assignment operator(=).
This is where we use this library function.
It copies one string to another.
Syntax
strcpy(string1,string2);
It copies the string from string2 to string1.
Usage
#include<stdio.h>
#include<string.h>
int main()
{
char name[]="Abhilekh";
char copyName[8];
strcpy(copyName,name);
printf("copyName is %s",copyName);
return 0;
}
The output is :
The string at copyName is Abhilekh.
Strcmp
It is used to compare two strings.It returns zero(0) if both the strings are same and the ASCII difference between them if they different.
Syntax
strcmp(string1,string2);
Usage
#include<stdio.h>
#include<string.h>
int main()
{
if(strcmp("Kathmandu","Kathman")==0)
printf("Both the strings are same");
else
{
printf("They are different");
}
return 0;
}
The output is:
They are two different strings
Strcat
It concatinates(joins) to different strings.
Syntax
strcat(string1,string2);
Both the string1 and string2 are concatinated together and the new string is stored in the first parameter of the function call .(string1 in this case).
Usage
#include<stdio.h>
#include<string.h>
int main()
{
char str1[10]="Abhilekh";
char str2[20]= "Gautam";
strcat(str2,str1);
printf("concatinated string is %s",str2);
}
The output is:
The concatinated form is GautamAbhilekh
Note where the new string is being stored.
Strlwr
It converts the string into the lowercased form.
Syntax
strlwr(string);
Usage
#include<stdio.h>
#include<string.h>
int main()
{
char name[]="ABHILEKH";
strlwr(name);
printf("Name:%s",name);
return 0;
}
The output is :
Name:abhilekh
Strupr
It returns the input string in the uppercased form.
Syntax
strupr(string);
Usage
#include<stdio.h>
#include<string.h>
int main()
{
char name[]="Abhilekh";
strupr(name);
printf("Name:%s",name);
return 0;
}
The output is :
Comments
Post a Comment