SrcForge

Lesson 15

Strings

A string in C is a sequence of characters stored in a character array and terminated by a special character called the null character ('\0'). C does not have a built-in string data type, so strings are represented using arrays of the char data type.

C Track

Save progress as you learn.

44 lessons

Lesson content

Strings in C Programming: A Complete Beginner to Advanced Guide

What are Strings in C Programming?

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

Unlike languages such as Java or Python, C does not have a built-in string data type. Instead, strings are represented using arrays of the char data type.

char name[] = "Alice";

Internally, the above string is stored character by character as A, l, i, c, e, followed by the null character marking the end.

Why Do Strings Exist?

Programs often need to work with text. Strings allow programs to:

  • Store names
  • Accept user input
  • Display messages
  • Read files
  • Process text
  • Build menus
  • Communicate with users

Without strings, handling text in C would be extremely difficult.

Real-World Use Cases

Strings are used almost everywhere:

  • Usernames and passwords
  • Email addresses
  • File names
  • URLs
  • Chat applications
  • Search engines
  • Configuration files
  • Command-line arguments
  • Text editors

Prerequisites

Before learning Strings in C Programming, you should understand:

  • Variables
  • Data types
  • Character (char) data type
  • Arrays
  • Loops (for, while)
  • Basic input and output (printf, scanf)

Core Concepts of Strings in C Programming

1. Declaring a String

A string is simply an array of characters.

Syntax

char string_name[size];

Example

char city[20];

This reserves space for 20 characters.

2. Initializing Strings

Method 1: Using Double Quotes

char name[] = "John";

Method 2: Character Array

char name[] = {'J','o','h','n','\0'};

Both methods produce the same string.

3. Null Character ('\0')

Every C string ends with '\0'. It marks the end of the string. Without it, C functions continue reading memory until they accidentally find one.

4. Accessing Characters

Each character has an index.

printf("%c", word[0]);

Output: H

5. Reading Strings

Using scanf()

scanf("%s", name);

Reads only until the first space. For input "John Smith", it stores "John".

Using fgets()

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

Reads spaces as well. Preferred for user input.

6. Printing Strings

printf("%s", name);

%s tells printf() to print an entire string.

7. Common String Library Functions

Include:

#include <string.h>
FunctionPurpose
strlen()Find length
strcpy()Copy string
strncpy()Copy up to a specified number of characters
strcat()Concatenate strings
strncat()Append up to a specified number of characters
strcmp()Compare strings
strncmp()Compare first n characters
strchr()Find first occurrence of a character
strstr()Find a substring

8. String Memory Representation

char name[] = "Cat";

Memory: C, a, t, followed by the null character ('\0').

Code Examples

Example 1: Beginner – Print a String

#include <stdio.h>                 // Include standard input/output library

int main()                         // Program entry point
{
    char name[] = "Alice";         // Store the string "Alice" in a character array

    printf("%s\n", name);          // Print the entire string

    return 0;                      // Indicate successful execution
}

Output: Alice

Example 2: Intermediate – Read and Display a String

#include <stdio.h>                 // Include standard input/output library

int main()                         // Program entry point
{
    char name[50];                 // Create a character array with room for 49 characters plus '\0'

    printf("Enter your name: ");   // Prompt the user

    fgets(name, sizeof(name), stdin); // Read a full line of input safely

    printf("Hello, %s", name);     // Display the entered string

    return 0;                      // End the program
}

Example 3: Intermediate – Find String Length

#include <stdio.h>                 // Include standard input/output library
#include <string.h>                // Include string handling functions

int main()                         // Program entry point
{
    char word[] = "Programming";   // Store a string

    int length = strlen(word);     // Calculate the string length (excluding '\0')

    printf("Length = %d\n", length); // Print the length

    return 0;                      // End the program
}

Output: Length = 11

Example 4: Intermediate – Compare Two Strings

#include <stdio.h>                 // Include standard input/output library
#include <string.h>                // Include string functions

int main()                         // Program entry point
{
    char password1[] = "admin";    // First string
    char password2[] = "admin";    // Second string

    if (strcmp(password1, password2) == 0) // Compare both strings
    {
        printf("Strings are equal.\n");    // Print if they match
    }
    else
    {
        printf("Strings are different.\n"); // Print if they do not match
    }

    return 0;                      // End the program
}

Example 5: Advanced – Reverse a String Without Library Functions

#include <stdio.h>                 // Include standard input/output library
#include <string.h>                // Include string functions for strlen()

int main()                         // Program entry point
{
    char text[] = "Programming";   // Original string

    int length = strlen(text);     // Find the string length

    printf("Reversed: ");          // Print a label

    for (int i = length - 1; i >= 0; i--) // Traverse from end to beginning
    {
        printf("%c", text[i]);     // Print one character at a time
    }

    printf("\n");                  // Move to the next line

    return 0;                      // End the program
}

Output: Reversed: gnimmargorP

Common Mistakes and Pitfalls

WrongCorrect
if(str1 == str2)if(strcmp(str1, str2) == 0)
gets(name);fgets(name, sizeof(name), stdin);
Forgetting '\0' in manually built stringsAlways terminate with '\0'
char name[5] = "Hello";char name[6] = "Hello";
Buffer overflow from long inputLimit input size with fgets() or width specifiers in scanf()

Wrong:

char a[] = "ABC";
char b[] = "ABC";

if (a == b)
    printf("Equal");

Correct:

char a[] = "ABC";
char b[] = "ABC";

if (strcmp(a, b) == 0)
    printf("Equal");

Best Practices

  • Prefer fgets() over gets() and often over scanf("%s") for user input.
  • Always allocate space for the null terminator.
  • Use strlen() instead of manually counting characters unless required.
  • Use strcmp() to compare string contents.
  • Include <string.h> when using string functions.
  • Check array sizes before copying or concatenating strings.
  • Favor bounded functions such as strncpy() and strncat() when appropriate, while understanding their behavior.

When NOT to Use This

Avoid fixed-size character arrays when:

  • The text length is unknown or can vary greatly.
  • You need to process very large strings.
  • Frequent resizing is required.

In these cases, dynamically allocated memory using functions such as malloc() and realloc() is often a better choice.

Summary / Key Takeaways

  • Strings in C programming are arrays of characters terminated by '\0'.
  • C does not provide a built-in string data type.
  • Strings are declared using char arrays.
  • The null character marks the end of a string.
  • Use %s to print strings with printf().
  • fgets() is generally safer than scanf("%s") for reading user input.
  • The <string.h> library provides useful functions like strlen(), strcpy(), strcat(), and strcmp().
  • Always leave room for the null terminator when allocating space.
  • Compare strings using strcmp(), not the == operator.
  • Protect against buffer overflows by limiting input sizes.

FAQ About Strings in C

1. Does C have a built-in string data type?

No. C represents strings as arrays of char ending with a null character ('\0').

2. Why is the null character important?

It tells C where the string ends. Without it, string functions may read beyond the intended memory, causing undefined behavior.

3. Why doesn't == work for comparing strings?

== compares memory addresses (for arrays that decay to pointers), not the characters inside the strings. Use strcmp() to compare string contents.

4. Which is better: scanf() or fgets() for reading strings?

fgets() is generally the better choice because it can read spaces and helps prevent buffer overflows by limiting the number of characters read.

5. What header file is required for string functions?

Include <string.h>. It provides standard string-handling functions such as strlen(), strcpy(), strcat(), and strcmp().