Chapter 20 of 44

Strings

So far, we've learned that char is used to store a single character.

But what if we want to store a word or a sentence like "Hello"?

That's where strings come in.

What is a String?

A string is a sequence of characters stored in a character array and terminated by a null character (\0) in C.

For example:

char name[] = "John";

Internally, it is stored like:

J   o   h   n   \0

The \0 marks the end of the string. So "John" needs 5 bytes of space: 4 characters plus the \0.


Declaring a String

Since C doesn't have a separate built-in string data type, strings are stored using char arrays.

char name[20];

This creates a character array that can hold a string, including its terminating \0.

We can also initialize it directly:

char name[] = "John";

Printing a String

We use %s with printf() to display a string.

char name[] = "John";

printf("%s", name);

Output:

John

Taking String Input

We can use scanf() to read a string:

char name[20];

scanf("%19s", name);

If the user enters:

John

the program stores "John" in name.

Notice that we don't use & before name here because the array name already represents the address of its first element in this context.

scanf("%s", ...) stops reading when it encounters whitespace, so it cannot read a full sentence containing spaces.

For example, if the user enters:

John Smith

only John would be read.


Reading a Full Line

To read a string containing spaces, fgets() is generally a safer choice:

char name[50];

fgets(name, sizeof(name), stdin);

This can read input such as:

John Smith

Note that fgets() also stores the newline character (\n) when the user presses Enter, if there is room for it in the array. You may need to remove it before using the string.

Never use the old gets() function. It cannot limit how many characters it reads, which can overflow the array, and it was removed from the C language in C11.


String Functions

C provides several useful functions for working with strings through the <string.h> header.

Function

Purpose

strlen()

Finds string length

strcpy()

Copies a string

strcat()

Joins strings

strcmp()

Compares strings (returns 0 if they are equal)

Example:

#include <stdio.h>
#include <string.h>

int main()
{
    char name[] = "John";

    printf("%zu", strlen(name));

    return 0;
}

Output:

4

strlen() returns the number of characters, not including the terminating \0.

Character vs String

This is an important difference:

char grade = 'A';       // Character
char name[] = "John";   // String

A character uses single quotes, while a string uses double quotes.

'A'      → Character
"John"   → String

In Simple Words

A string in C is a sequence of characters stored in a character array and ending with \0.

For example:

char name[] = "John";

Understanding strings is important because they are used everywhere—from names and messages to text processing and user input.