String in C Program with Example

String in C Program with Example

We can define the C Programming String as it is a Character’s arrays. Basically String in C program means that a complete string is a combination of characters. And this character is stored in an array to form a complete string. It is only because C programming language has no String type of data type.

This character of an array is a one-dimensional array that is terminated by a null(‘\0’). This null help to identify the end of the character array.

Each Character occupies one byte of Memory.

We can say that Strings are the form of data used in programming for storing and manipulating text, such as words, names, and sentences.

Declaration of String in C

We can declare a string easily as we declare an array. Below is the fundamental syntax structure for declaring a string.

char str_name[size]

In the above syntax structure, str_name is any name given to the string variable as well as size is used to define the size of the string, i.e the number of characters strings will certainly keep. Please keep in mind that there is an additional ending character which is the Null character (‘\ 0’) used to show the termination of string which varies in strings from normal character arraysString Example:-

Here is a bunch of operations we can perform on string

Example 1: Print String in C Program

#include <stdio.h>
int main()
{
    char str1[20] = {'T','u','t','o','r','i','a','l','w','o','r','l','d','\0'};
    char str2[]="Tutorialworld";
    printf("String1 = %s.", str1);
    printf("\nString2 = %s.", str2);
    return 0;
}

Output

String1 = Tutorialworld.
String2 = Tutorialworld.

Let’s see another example of string in C programming language for better understanding. In this example, we will see how ‘/0’ is working.

Example 2: C Program to calculate the length of string

#include <stdio.h>
int main()
{
    char s[] = "tutorial world is educational website";
    int i;
    for (i = 0; s[i] != '\0'; ++i);
    printf("Length of string is %d", i);
    return 0;
}

Output :

Length of string is 37

With the help of the above program, you can realize the space is also calculated as a string in C. So we cannot ignore the space while counting the size of the char array which forms a string.