Table of Contents
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 |
strlen | To calculate the length of the string. |
strcat | Add one string at the end of another. |
strncat | Adds the first n character of a string at the end of another string.. |
strcpy | Copies one string into another. |
strncpy | First n characters of one string are copied into another. |
strcmp | Make a comparison between two strings |
strncmp | The first n characters of two strings are compared. |
strchr | The first occurrence of a given character in a string will be searched. |
strrchr | The last occurrence of a given character in a string will be searched. |
strstr | This 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
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:
- White space is also calculated in the length of the string.
- ‘\0’ i.e., the null character is counted in string length.
0 Comments