Most Commonly used String Functions in C, C++



Here are the most commonly used string library functions.
Firstly, if you want to use these functions, you will have to add string header file in your program. Just like this:
#include<string.h>
Now let’s get a watch on the functions!
1) strcpy();
It is used to copy one string to another. Here is a example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
main()
{
char a[10]="Bello";
char b[10];
strcpy(b,a);
printf("%s",b);
getch();
}
Output: Bello
Syntax: strcpy(destination_variable,source_variable);
2)strcat();
It is used to concatenate two strings, that is, to append them. See the example below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
main();
{
char a[20],b[10],;
a="Good";
b="Morning";
strcat(a,b);
printf("%s"a);
getch();
}
Output:
GoodMorning
Syntax: strcat(destination_variable,source_variable);
3) strlen();
It is used to get the length of the string that we pass in it. Get cleared by the example given below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
main()
{
 int length;
 char a[100];
 printf("Enter your name : ");
 gets(a);
 length=strlen(a);
 printf("\nThe length of your name is : %s",a);
 getch();
}
Output:
Enter your name : yash
The length of your name is : 4
Logic : It actually counts the words till it gets ‘\0’ in to your word.
4) strcmp();
It is used to compare two strings, if they are same or not. Here is one example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
main();
{
 char a[10],b[10];
 int true;
 printf("Enter string 1 : ");
 scanf("%s",a);
 printf("\nEnter string 2 : ");
 scanf("%s",b);
 output=strcmp(a,b);
 if(output==0)
 {
  printf("\nBoth are equal");
 }
 else
 {
  printf("\nBoth are different");
 }
 getch();
}
Output:
Enter string 1 : i want equal
Enter string 2 : i want equal
Both are equal
5) strlwr();
It will change all the letters and characters into lowercase.
6) strupr();
It will change all the letters and characters into uppercase.
I don’t think you need example for last two, anyways, stay tuned for more content.

Related Posts with Most Commonly used String Functions in C, C++