What if a word or a sentence is needed to be stored in a variable? One way to do this is using a character array. There is a more convenient way, to store them as strings.

What is a string?

A string is an array of characters that is terminated with a null terminator. The null terminator is a special character ‘\0’, which has the numerical value of 0. It is used to represent emptiness. So, in the case of a string, the null terminator denotes where the string ends. So, can’t we just use an empty char to terminate? No, char cannot accept empty values. It does not work like that. That is why a null terminator is used.

Comparing strings

To compare strings, we need to include ‘string.h’.

#include <string.h>

This header file provides some functions or ways to do some operations on strings. The ‘strcmp()’ is used to compare strings.

strcmp(string1, string2);

Assigning to a string

String assignment does not work in the usual way.

char myCar[] = "BMW";
char myNewCar[] = "Tesla";

myCar = myNewCar;
printf("%s", myCar);

Reading strings

Reading string input from the user is a bit different.

char name[30];
scanf("%s", name);

Usually, an ampersand is placed before the variable to which the input value is to be stored.

int num;
scanf("%d", &num);

Sample Quiz Program

Let’s make a small quiz program from all the knowledge we acquired through this and previous articles.

#tutorial #c-programming #programming-tips #programming

String — An array of characters with ‘\0’
2.05 GEEK