string functions in C

String Function:

The standard library for C string functions is string.h. This header file defines tons of useful string manipulation functions including:
  • strcmp
  • strcat
  • strcpy
  • strlen
strcmp:
strcmp() in C programming language is used to compare two string. If both the strings are equal then it gives the result as zero but if not then it gives the numeric difference between the first non matching character in the string.

Syntax:

int strcmp(const char *str1, const char *str2);

Example:

int main()
{
   char str1[30], str2[30];
   printf("Enter first string : ");
   scanf("%s", &str1);
   printf("Enter second string : ");
   scanf("%s", &str2);
   if(strcmp(str1, str2)==0))
      printf("Both strings are equal.")
   else
      printf("strings are not equal.");
   return 0;
}

Output:


Enter first string : studycodemaster
Enter second string : studycodemaster
Both strings are equal.

strcat:
The strcat() function is used for string concatenation in C programming language. Which means this function is used to join the two string together.

Syntax:

strcat(string1, string2);

Example:

int main()
{
   char string1[50]="www.studycodemaster";
   char string2[5]=".blogspot.com";
   printf("Before concatenation the strings are : ");
   printf("\nstring1 : %s", string1);
   printf("\nstring2 : %s", string2);
   printf("\nAfter concatenation the string is : ")
   printf("string : %s", strcat(string1, string2));
   return 0;
}

Output:


Before concatenation the strings are :
string1 : www.studycodemaster
string2 : .blogspot.com
After concatenation the string is :
string : www.studycodemaster.blogspot.com

strcpy:
strcpy() function is used to copies a string from a source location to a destination location and provides a null character to terminate the string.

Syntax:

strcpy(destination, source);

Example:

int main()
{
   char string1[50], string2[50];
   printf("Enter string : ");
   scanf("%s", &string1);
   strcpy(string2, string1);
   printf("string1 : %s ", string1);
   printf("string2 : "%s , string2);
   return 0;
}

Output:


Enter string : www.studycodemaster.blogspot.com
string1 : www.studycodemaster.blogspot.com
string2 : www.studycodemaster.blogspot.com

strlen:
The strlen() is used to calculate the length of the string. Which means strlen function counts the total number of characters present in the string which includes alphabets, numbers, and all special characters including blank spaces.

Syntax:

count = strlen(stringvariable);

Example:

int main()
{
   char str[20];
   printf("Enter a string : ");
   scanf("%s", &str);
   printf("Length of the string is : %d", strlen(str));
   return 0;
}

Output:

Enter a string : www.studycodemaster.blogspot.com
Length of the string is : 32

Post a Comment Blogger

 
Top