String Functions

String Functions


In C, we have various in-build functions which we can access using header files.
In C, we have a header file named as string.h
This file includes string operations like strlen(), strcpy(), strcat() and strcmp().

strlen()

strlen() this is a function defined in string.h which finds length of string.
It neglects \0 while counting length.
It returns a integer value because length of string will be always an integer value.
Its syntax is:
strlen(string_name)
It takes string name as argument and gives integer as output.

strcpy()

strcpy() this is a function defined in string.h which copies one string into another string.
It has no return type.
Its syntax is:
strcpy(string1,string2)
It is function which accepts 2 strings as input.
It will copy string2 content in string1.
We can enter 2nd string manually also.
e.g: strcpy(string1,"Hello") 
This will create Hello as string and string1 will be pointer pointing to that string.

strcat()

strcat() this is a function defined in string.h which concatenates one string into another string.
It has no return type.
Its syntax is:
strcpy(string1,string2)
It is function which accepts 2 strings as input.
It will concatenate string2 content with string1.
e.g: 
Suppose string 1 is "Learn C " and 2nd string is "in simple words!!!"
strcat(string1,string2) ;
Now string 1 becomes: "Learn C in simple words!!!" and 2nd string is "in simple words!!!"

strcmp()

strcmp() this is a function defined in string.h which compares ASCII values of charcters in string and return an integer number.
If integer number is 0 then strings are equal else strings are not equal.
Its syntax is:
strcmp(string1,string2)
It takes two strings as argument and gives integer as output.

Let's see program to clear concept regarding above discussion:


#include<stdio.h>
#include<string.h>                          // Note //
void main()
{
char a[10],b[10];
int m;
printf("Enter 1st string: ");
gets(a);                                    // To get string along with spaces//
printf("Entered string is : ");
puts(a);
printf("Enter 2nd string: ");
gets(b);
printf("Entered string is : ");
puts(b);
m=strcmp(a,b);                  // It returns an int value //
if(m==0)
{
printf("\nStrings are equal!!!\n");
}
else
{
printf("\nStrings are not equal!!!\n");
}
printf("\nLength of 1st string is: %d",strlen(a));               // It returns an int value //
printf("\nLength of 2nd string is: %d",strlen(b));
strcat(a,b);                             // It returns no value //
printf("\nConcatinated string is : ");
puts(a);
strcpy(a,b);                           // It returns no value //
printf("Copied string is : ");
puts(a);
m=strcmp(a,b);
if(m==0)
{
printf("\nStrings are equal!!!");           /*Here, everytime condition will be true since we have used strcpy() function due to which both strings have same value*/
}
else
{
printf("\nStrings are not equal!!!");
}
}

Output:



No comments:

Post a Comment