A Learning Platform

SUCCESS

Success = Discipline + Consistency + Sacrifice.
Discipline - in what you do.
Consistency - in what you do.
Sacrifice - for what you do.

                   -- Manjunatha C. P. --

string.h: String handling functions in C

All the string handling library functions in C are present in string.h header file.

Using string library functions we can perform following operations on strings:

  1. Find the string length.
  2. Copy string.
  3. Concatenate(join) string.
  4. Comparison of string.
  5. Reverse a string.
  6. Covert string to lowercase.
  7. Convert string to uppercase.

Following are the important string handling library functions in C:

strlen(string_name) : returns the length of string.
strcpy(destination, source) : copies the contents of source string to destination string.
strcat(first_string, second_string) : joins first string with second string. The result of the string is stored in first string.
strcmp(first_string, second_string) : compares the first string with second string. If both strings are same, it returns 0.
strrev(string) : returns the reverse of string.
strlwr(string) : returns string characters in lowercase.
strupr(string) : returns string characters in uppercase.

Example program: String handling functions in C

#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char s1[20],s2[20];
int l;
printf("Enter string 1: ");
scanf("%s",s1);
printf("Enter string 2: ");
scanf("%s",s2);
l=strlen(s1);
printf("Length of string 1: %d\n",l);
l=strlen(s2);
printf("Length of string 2: %d\n",l);
printf("String comparison: ");
if(strcmp(s1,s2)==0)
    printf("Strings are equal\n");
else
  printf("Strings are not equal\n");
printf("Upper case of string 1: %s\n",strupr(s1));
printf("Loweer case of string 2: %s\n",strlwr(s2));
printf("String concatenation:\n");
strcat(s1,s2);
printf(" string 1: %s\n",s1);
strcpy(s1,s2);
printf("After copy strings are\n");
printf(" string 1: %s\n",s1);
printf("string 2: %s\n",s2);
printf("Reverse of string 2: %s\n",strrev(s2));
getch();
}

Output 1:

Enter string 1: my
Enter string 2: COLLEGE
Length of string 1: 2
Length of string 2: 7
String comparison: Strings are not equal
Upper case of string 1: MY
Lower case of string 2: college
String concatenation:
string 1: MYcollege
After copy strings are
string 1: college
string 2: college
Reverse of string 2: egelloc

Output 2:

Enter string 1: learning
Enter string 2: learning
Length of string 1: 8
Length of string 2: 8
String comparison: Strings are equal
Upper case of string 1: LEARNING
Lower case of string 2: learning
String concatenation:
string 1: LEARNINGlearning
After copy strings are
string 1: learning
string 2: learning
Reverse of string 2: gninrael

QUIZ:

1] All string handling functions in C are present in header file.
  1. math.h
  2. string.h
  3. ctype.h
  4. conio.h
2] String handling function in C used to copy one string to another is.
  1. copy()
  2. strcopy()
  3. strcpy()
  4. None