📚 C Programming Tutorial

C Programming

Learn C programming concepts with simple explanations, examples and practical notes.

← Back to C Programming

Strings

What is a string in C?

A string in C is a sequence of characters terminated by a special null character ('\0').

C languages does not have a separate built-in string data type. Instead, strings are represented using arrays of characters.

Example:

char name[6] = "Hello";

The string is stored as follows:
H - Index 0
e - Index 1
l - Index 2
l - Index 3
o - Index 4
\0 - Index 5

The first five positions store letters. The final position stores the null character, which marks the end of the string.

Here:
- char is the data type used to store characters.
- name is the array name.
- 6 is the total array capacity.
- "Hello" is the string being stored.
- '\0' indicates the end of the string.

Important: The string "Hello" contains 5 visible characters, but it requires 6 array elements when stored as a null-terminated C string.

Character vs string

Character String
Represents one character Represents a sequence of characters
Written using single quotes Written using double quotes
Example: 'A' Example: "Apple"
Commonly stored in char Commonly stored in a char array
char ch = 'A';
char word[] = "Apple";

Remember the difference:
- 'A' is a character constant.
- "A" is a string containing 'A' followed by '\0'.

Declaring a string

A string is generally declared using a character array.

Syntax:

char string_name[size];

Example:

char name[20];
char city[30];
char message[100];

Explanation:
- name can hold up to 19 visible characters as a null-terminated string.
- city can hold up to 29 visible characters.
- message can hold up to 99 visible characters.

One array position must be reserved for '\0' when the array is used to store a null-terminated string.

Initializing a string

Strings can be initialized in several ways.

Method 1: Using a string literal

char name[6] = "Hello";

The compiler stores the characters and the terminating null character.

Method 2: Allowing the compiler to determine the size

char name[] = "Hello";

The compiler automatically allocates 6 elements, including '\0'.

Method 3: Initializing character by character

char name[] = {'H', 'e', 'l', 'l', 'o', '\0'};

The null character is explicitly included.

Method 4: Initializing an empty string

char name[20] = "";

The first element is '\0', so the string is initially empty.

Important difference

char a[5] = "Hello";  /* No space for '\0' */
char b[6] = "Hello";  /* Space for '\0' */

In the first declaration, the array has no room for the terminating null character. It should not be treated as a valid null-terminated string. The second declaration is suitable for storing "Hello" as a C string.

How does a string work in memory?

Consider:

char word[] = "CAT";

The characters C, A, and T are stored at indexes 0, 1, and 2, and the null character is stored at index 3.

The null character is essential because C's standard string-handling mechanisms use it to determine where the string ends. Without a terminating '\0', operations that expect a string may read beyond the array, causing undefined behavior.

Reading and displaying strings

A. Reading a single word using scanf()

The %s format specifier reads characters until whitespace is encountered.

#include <stdio.h>

int main( )
{
    char name[20];

    printf("Enter your name: ");
    scanf("%19s", name);

    printf("Your name is %s\n", name);

    return 0;
}

Sample output:

Enter your name: Ravi
Your name is Ravi

Why %19s? It limits the input to 19 characters, leaving one position for '\0' in the 20-element array.

Note that scanf("%s", name) does not read a full name containing spaces. For example, entering Ravi Kumar stores only Ravi.

B. Reading a line using fgets()

fgets() can read a line containing spaces and is generally safer than unbounded input methods.

#include <stdio.h>

int main( )
{
    char name[50];

    printf("Enter your full name: ");

    if (fgets(name, sizeof name, stdin) != NULL)
    {
        printf("Your name is %s", name);
    }

    return 0;
}

Sample output:

Enter your full name: Ravi Kumar
Your name is Ravi Kumar

fgets() may store the newline character if there is room for it. It also adds a terminating null character when it successfully reads input.

C. Displaying a string using printf()

#include <stdio.h>

int main( )
{
    char city[] = "Hyderabad";

    printf("%s\n", city);

    return 0;
}

Output:

Hyderabad

Here, %s displays characters until the terminating null character is reached.

Accessing individual characters in a string

Each character in a string can be accessed using its array index. Indexing starts at 0.

Example:

#include <stdio.h>

int main( )
{
    char word[] = "APPLE";

    printf("%c\n", word[0]);
    printf("%c\n", word[1]);
    printf("%c\n", word[4]);

    return 0;
}

Output:

A
P
E

The expression word[0] accesses the first character, while word[4] accesses the fifth character.

Traversing a string using a loop

A string can be traversed character by character until the null character is encountered.

#include <stdio.h>

int main( )
{
    char word[] = "HELLO";
    int i = 0;

    while (word[i] != '\0')
    {
        printf("%c\n", word[i]);
        i++;
    }

    return 0;
}

Output:

H
E
L
L
O

Finding the length of a string without library functions

The length of a string is the number of characters before '\0'. The terminating null character is not counted.

Program:

#include <stdio.h>

int main( )
{
    char str[100];
    int i = 0;

    printf("Enter a string: ");
    scanf("%99s", str);

    while (str[i] != '\0')
    {
        i++;
    }

    printf("Length of string = %d\n", i);

    return 0;
}

Output:

Enter a string: COMPUTER
Length of string = 8

Explanation

  1. Initialize i to 0.
  2. Check whether str[i] is different from '\0'.
  3. Increment i for each character.
  4. When the null character is reached, i contains the length.

For a string of length n, the loop performs n character checks before stopping.

Copying one string to another without library functions

String copying means copying every character from the source string to the destination, including the terminating null character.

#include <stdio.h>

int main( )
{
    char source[] = "HELLO";
    char destination[20];
    int i = 0;

    while (source[i] != '\0')
    {
        destination[i] = source[i];
        i++;
    }

    destination[i] = '\0';

    printf("Source      : %s\n", source);
    printf("Destination : %s\n", destination);

    return 0;
}

Output:

Source      : HELLO
Destination : HELLO

Important points:
- The source characters are copied one by one.
- The destination must have enough space.
- The null character must also be copied or added.
- destination[i] = '\0'; terminates the copied string.

Joining two strings without library functions

Joining strings is also called concatenation. The second string is copied to the end of the first string.

#include <stdio.h>

int main( )
{
    char first[30] = "Hello ";
    char second[] = "World";
    int i = 0;
    int j = 0;

    /* Find the end of the first string */
    while (first[i] != '\0')
    {
        i++;
    }

    /* Copy second string to the end of first */
    while (second[j] != '\0')
    {
        first[i] = second[j];
        i++;
        j++;
    }

    first[i] = '\0';

    printf("Combined string: %s\n", first);

    return 0;
}

Output:

Combined string: Hello World

How does it work?

  1. The first loop finds the position of the null character in first.
  2. The second loop copies characters from second starting at that position.
  3. A new '\0' is added at the end.

The destination array must have sufficient capacity for both strings and the final null character.

Comparing two strings without library functions

Two strings are compared character by character. If all corresponding characters are equal and both strings end at the same position, the strings are equal.

#include <stdio.h>

int main( )
{
    char first[50];
    char second[50];
    int i = 0;

    printf("Enter first word: ");
    scanf("%49s", first);

    printf("Enter second word: ");
    scanf("%49s", second);

    while (first[i] == second[i] &&
           first[i] != '\0' &&
           second[i] != '\0')
    {
        i++;
    }

    if (first[i] == second[i])
    {
        printf("Strings are equal\n");
    }
    else
    {
        printf("Strings are not equal\n");
    }

    return 0;
}

Example output:

Enter first word: apple
Enter second word: apple
Strings are equal

Another example:

Enter first word: apple
Enter second word: mango
Strings are not equal

Why check the null character? If one string ends before the other, the strings are different even when all earlier characters match.

This program checks equality, not alphabetical ordering.

Reversing a string without library functions

Reversing a string means displaying its characters in the opposite order. The following program uses a second array to store the reversed string.

#include <stdio.h>

int main( )
{
    char str[100];
    char rev[100];
    int i = 0;
    int j = 0;

    printf("Enter a word: ");
    scanf("%99s", str);

    while (str[i] != '\0')
    {
        i++;
    }

    while (i > 0)
    {
        rev[j] = str[i - 1];
        j++;
        i--;
    }

    rev[j] = '\0';

    printf("Reversed string: %s\n", rev);

    return 0;
}

Output:

Enter a word: HELLO
Reversed string: OLLEH

The first loop finds the length. The second loop copies the characters from the end to the beginning and then adds '\0'.

Counting vowels and consonants without library functions

#include <stdio.h>

int main( )
{
    char str[100];
    int i = 0;
    int vowels = 0;
    int consonants = 0;
    char ch;

    printf("Enter a word: ");
    scanf("%99s", str);

    while (str[i] != '\0')
    {
        ch = str[i];

        if (ch >= 'A' && ch <= 'Z')
        {
            ch = ch + ('a' - 'A');
        }

        if (ch >= 'a' && ch <= 'z')
        {
            if (ch == 'a' || ch == 'e' ||
                ch == 'i' || ch == 'o' ||
                ch == 'u')
            {
                vowels++;
            }
            else
            {
                consonants++;
            }
        }

        i++;
    }

    printf("Vowels      = %d\n", vowels);
    printf("Consonants  = %d\n", consonants);

    return 0;
}

Output:

Enter a word: Education
Vowels      = 5
Consonants  = 4

This program counts English alphabetic characters only. Spaces, digits, and punctuation are ignored. It converts uppercase letters to lowercase using character arithmetic before checking for vowels.

Reading a string character by character

Another way to read a string is to use a loop and the %c format specifier. This approach helps students understand how characters are stored in an array.

#include <stdio.h>

int main( )
{
    char str[6];
    int i;

    printf("Enter 5 characters: ");

    for (i = 0; i < 5; i++)
    {
        scanf(" %c", &str[i]);
    }

    str[5] = '\0';

    printf("String = %s\n", str);

    return 0;
}

Example output:

Enter 5 characters: HELLO
String = HELLO

The space before %c skips whitespace left in the input stream. The program stores exactly five characters and adds '\0' at index 5.

Modifying characters in a string

When a string is stored in a modifiable character array, individual characters can be changed using their indexes.

#include <stdio.h>

int main( )
{
    char str[] = "HELLO";

    str[0] = 'Y';

    printf("%s\n", str);

    return 0;
}

Output:

YELLO

However, a string literal must not be modified through a pointer.

char *str = "HELLO";

In this declaration, str points to a string literal. Attempting to modify its characters, such as str[0] = 'Y';, causes undefined behavior.

Use a character array when you need to modify the string:

char str[] = "HELLO";
str[0] = 'Y';

String input: important differences

Method Reads spaces? Main point
scanf("%s", str) No Stops at whitespace
scanf("%99s", str) for char str[100] No Limits input width
fgets(str, sizeof str, stdin) Yes Reads a line, possibly including newline
Repeated scanf(" %c", &str[i]) Depends on format Reads characters individually; the leading space skips whitespace

These are input/output functions from the standard C library, not string-handling functions from string.h. The examples above do not use strlen(), strcpy(), strcat(), or strcmp().

Common mistakes in strings

❌ Mistake 1: Forgetting the null character

char str[3] = {'C', 'A', 'T'};

This array does not contain a terminating '\0'. It is not a valid null-terminated C string.

❌ Mistake 2: Insufficient array size

char str[5] = "Hello";

There is no space for the null character. Use char str[6] = "Hello";.

❌ Mistake 3: Using == to compare string contents

if (first == second)

This compares pointer or array-related expressions in ways that do not test whether two strings have identical contents. Use a character-by-character comparison.

❌ Mistake 4: Reading beyond the array

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

An unbounded %s may write more characters than the array can hold. Specify a field width, such as %9s, or use fgets().

Quick revision

Concept Key point
String Sequence of characters terminated by '\0'
Declaration char name[20];
Initialization char name[] = "Naveen";
Accessing a character name[0]
Traversing a string Loop until name[i] == '\0'
String length Count characters before '\0'