Using the C String.h Library Functions
We will use the three most important functions of the “string.h” header file in the following examples:
Example 1: Using the String Length Function
The string length function of the “string.h” header file is used to calculate the length of a string. The following C script makes use of this function:
In this program, we declared a “sample” string and assigned the “Programming” string to it. Then, we used the “strlen” function of the “string.h” library to calculate the length of this string and assigned it to the “length” variable. After that, we printed this length on the terminal.
To compile this C program, the following command is used:
To execute this program, the following command is used:
The length of our string is shown in the following image:
Example 2: Using the String Copy Function
The string copy function of the “string.h” library is used to copy one string to another. The following C script is designed to serve this purpose:
In this example, we used the same string as in the previous example. Apart from that string, we declared another string which is “sample2”. Using the “strcpy” function of the C programming language, we copied the “sample” string to “sample2”. After that, we printed the “sample2” string on the terminal.
The following output depicts that our first string is successfully copied to the second string:
Example 3: Using the String Comparison Function
The string comparison function of the “string.h” header file is used to compare two strings. The output of this function turns out to be “0” when both strings are exactly identical. Otherwise, this function returns the difference between the ASCII values of the very first non-matching pair of characters of both strings. The following C program makes use of this function:
In this program, we declared two different strings. After that, we used the “strcmp” function to compare these two strings and store their difference in the “comparison” variable. Then, we printed the value of the “comparison” variable on the terminal.
The difference between our two strings is shown in the following image:
This article is centered around the “string.h” header file of the C programming language. In this regard, we discussed a few functions of this library in this guide. Now, you can easily explore the other functions of this library on your own.