This tutorial is about strings in C Programming Language. The understanding of strings requires a good knowledge of array. The reason because string is nothing but a one-dimensional array of characters. There is no built-in data type, so we use arrays to work with strings. The simplest example is shown below.
In this example, we have declared character array Word which hold string foobar. This one dimensional array of characters terminates with NULL Character ‘\0’. Our array consists of 6 characters but we have declared Word array of size 7. This is because we always have to use extra character for NULL termination character.
Example: This example code print string of characters “foobar”. The use of character array to print string on screen is easiest method. In further lesson, we will use string library function.
[crayon-5c6ac0e2b941b958997930/] Explanation: The run and build this example code will simply print “foobar” on screen. There is not much to discuss in this code snippet. The only new symbol is %s. This %s is format specifier used for array of char sequence of characters i.e. string. The printf statement simply prints this string on screen.
C Language supports various functions under the <string.h> standard header file. C programmer often find raw string cumbersome to deal with. This is a reason why programmer include #include <string.h> header file in the beginning of code and enjoy built in function. Here are list of functions supported by <string.h> library.
|strcpy||copy a string|
|strcat||concatenate two strings|
|strlen||get string length|
|strchr||string scanning operation|
|strcmp||compare two strings|
|strncat||concatenate one string with part of another|
|strncmp||compare parts of two strings|
|strncpy||copy part of a string|
|strrchr||string scanning operation|
Example: This example uses couple of build in functions to copy a string, concatenate two strings and print the length of given string. The remaining functions and their uses will be covered in future lesson.
[crayon-5c6ac0e2b942e526955660/] Let’s build and run this example code and observe output. The output from this program is:
Explanation: The first few lines declare three strings str1, str2, str3 and one integer variable length. The strcpy(str3, str1) statement copy content of str1 into str3. So when we call to print str3. We will get Binary printed on a screen. The strcat( str1, str2) statement use to concatenate (link together in series) str1 and str2. This will result in printing BinaryUpdates on screen. The strlen(str1) statement return a length of string str1. Which will be then printed using printf statement.
This is it for Strings in C Programming. We hope you have enjoyed reading this lesson. In next lesson, we’ll learn about Structures, Typedef and Union in C Programming. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading.