Predefined string functions using C

Introduction

There are some string functions that are pre-defined and perform a specific task on the strings.

For example, the joining of 2 strings is called concatenation, finding the length of a string, comparison between two strings, etc. For performing such tasks there is no need of defining a function by ourselves because we are provided with some predefined string functions which will perform all these operations.

A list of all such functions is given below:

Function Use
strlenTo calculate the length of the string.
strcatAdd one string at the end of another.
strncatAdds the first n character of a string at the end of another string..
strcpyCopies one string into another.
strncpyFirst n characters of one string are copied into another.
strcmpMake a comparison between two strings
strncmpThe first n characters of two strings are compared.
strchrThe first occurrence of a given character in a string will be searched.
strrchrThe last occurrence of a given character in a string will be searched.
strstrThis will find the first occurrence of a given string in another string.

 

All the above-written functions are defined in “string.h” header file, so we need to include this header file by writing “#include<string.h>” in our code while using these functions.

strlen, strcpy, strcat, strcmp, are the most commonly used functions. And let’s write a program in which we will use all these functions.

Program

#include<stdio.h>
#include<string.h>
int main()
{
            char name[20];
            char str[]="Hello world";
            printf("Enter your name:\n");
            scanf("%s",name);
            int l1, l2;
            l1= strlen(name);
            l2= strlen(str);
            printf("length of '%s' is : %d\n",name,l1);
            printf("length of '%s' is : %d",str,l2);
            return 0;
}

 

Output

Predefined string functions using C

 

Explanation

Two string variables are declared in the above program i.e., ‘str’ which is assigned with the string “Hello world” and the other is ‘name’ in which the user will enter his name.

Both string variables are passed in the strlen function and the length is shown in the output screen.

Note:

  1. White space is also calculated in the length of the string.
  2. ‘\0’ i.e., the null character is counted in string length.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.