Preview
String functions in c language with examples
We should use string.h header file in a program to use string functions in a C program. Various string functions are:
1. strcpy()
This function can be used to copy some value into a string variable
Syntax: strcpy(Target, Source);
Target is the string variable in which want to store the value.
Source is the string value which we want to store in string variable Target.
char sname[20];
strcpy(name,”Rohit”);
Program to demonstrate the use of strcpy() function. |
#include<stdio.h> #include<string.h> int main() { char name[20]; strcpy(name,”Rohit”); printf(“name=%s”,name); return(0); } |
Output |
name=Rohit |
2. strncpy()
It can be used to copy particular number of characters from one string value to a string variable.
Syntax : strcpy(Target, Source,N);
Program |
#include<stdio.h> #include<string.h> int main() { char name1[10]=”Rohit”; char name2[10]; strncpy(name2,name1,3); return(0); } |
Output |
Name=Roh |
3. strcat()
It can be used to join values of two string variables.
Syntax: strcat(Target, Source);
Target is the string variable whose value we want to combine with another string value.
Source is the string value which we want to join with the value of another string variable.
Program |
#include<stdio.h> #include<string.h> int main() { char name[20]=”Rohit”; strcat(name,” Sharma”); printf(“\nname=%s”,name); return(0); } |
Output |
Studentname=Rohit Sharma |
4. strlen()
This function can be used to find number of characters in a string value.
Program |
#include<stdio.h> #include<string.h> int main() { char name[20]=”Rohit”; printf(“\nNumber of characters=%d”,strlen(name);); return(0); } |
Output |
Number of characters=5 |
5. strrev()
This function can be used to reverse string value.
Program |
#include<stdio.h> #include<string.h> int main() { char name[20]=”Rohit”; strrev(name); printf(“\nname=%s”,name); return(0); } |
Output |
Studentname=tihoR |
6. strcmp()
This function can be used to compare values two string values. It always returns 0 if the values to be compared are same.
Program |
#include<stdio.h> #include<string.h> int main() { char name[25]; strcpy(name,”Amita”); if(strcmp(name,”Rohit”)= =0) cout<<”\nHello”; else cout<<”\nWrong name”; return(0); } |
Output |
Hello |
7. strlwr()
This function can be used to convert the a string value to small case letters.
Program |
#include<stdio.h> #include<string.h> int main() { char name[20]=”ROHIT”; strlwr(name); printf(“\nname=%s”,name); return(0); } |
Output |
Studentname=rohit |
8. strupr()
This function can be used to convert the lower case letters to uppercase.
Program |
#include<stdio.h> #include<string.h> int main() { char name[20]=”rohit”; strupr(name); printf(“\nname=%s”,name); return(0); } |
Output |
Studentname=ROHIT |
Best Books of Computer Science