</>
Skip to content
C lessons (20/28)

C — Strings

String basics

C strings are arrays of char terminated by \0 (null byte):

#include <stdio.h>

int main() {
    // String literal
    char greeting[] = "Hello";  // {72, 101, 108, 108, 111, 0}

    // Explicit initialization
    char name[6] = {'A', 'l', 'i', 'c', 'e', '\0'};

    // Pointer to string literal
    const char *msg = "World";

    printf("%s\n", greeting); // Hello
    printf("%s\n", name);     // Alice
    printf("%s\n", msg);      // World

    // String length
    printf("Length: %zu\n", sizeof(greeting) - 1); // 5
    return 0;
}

String input

#include <stdio.h>

int main() {
    char name[50];

    // scanf: stops at whitespace
    printf("Enter name: ");
    scanf("%49s", name); // Limit to 49 chars + null
    printf("Name: %s\n", name);

    // fgets: reads entire line (recommended)
    char line[100];
    printf("Enter full name: ");
    fgets(line, sizeof(line), stdin);
    // Remove trailing newline
    line[strcspn(line, "\n")] = '\0';
    printf("Full name: %s\n", line);

    return 0;
}

String functions (<string.h>)

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

int main() {
    char str1[50] = "Hello";
    char str2[] = "World";

    // Length
    printf("Length: %zu\n", strlen(str1)); // 5

    // Concatenate
    strcat(str1, " ");
    strcat(str1, str2);
    printf("Joined: %s\n", str1); // Hello World

    // Copy
    char dest[20];
    strcpy(dest, "Hello");
    printf("Copied: %s\n", dest);

    // Safe versions (recommended)
    strncat(dest, " World", sizeof(dest) - strlen(dest) - 1);
    strncpy(dest, "Hello", sizeof(dest) - 1);
    dest[sizeof(dest) - 1] = '\0';

    // Compare
    printf("Compare: %d\n", strcmp("abc", "def"));  // Negative
    printf("Compare: %d\n", strcmp("abc", "abc"));  // 0
    printf("Compare: %d\n", strcmp("def", "abc"));  // Positive

    return 0;
}

Finding characters and substrings

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

int main() {
    char text[] = "Hello, World!";

    // Find first occurrence
    char *pos = strchr(text, 'W');
    if (pos) {
        printf("Found 'W' at index: %ld\n", pos - text);
    }

    // Find last occurrence
    char *last = strrchr(text, 'l');
    if (last) {
        printf("Last 'l' at index: %ld\n", last - text);
    }

    // Find substring
    char *sub = strstr(text, "World");
    if (sub) {
        printf("Found: %s\n", sub); // World!
    }

    // Find any character from a set
    char *any = strpbrk(text, "aeiou");
    if (any) {
        printf("First vowel: %c at index %ld\n", *any, any - text);
    }

    return 0;
}

Tokenizing strings

Split a string by delimiters:

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

int main() {
    char csv[] = "apple,banana,cherry,date";

    char *token = strtok(csv, ",");
    while (token != NULL) {
        printf("Token: %s\n", token);
        token = strtok(NULL, ",");
    }
    // Token: apple
    // Token: banana
    // Token: cherry
    // Token: date

    return 0;
}

String conversion

#include <stdio.h>
#include <stdlib.h>

int main() {
    // String to number
    int num = atoi("42");
    float pi = atof("3.14");
    long big = atol("1000000");

    printf("int: %d, float: %.2f, long: %ld\n", num, pi, big);

    // Number to string
    char buf[20];
    sprintf(buf, "%d", 42);
    printf("String: %s\n", buf);

    // Safer version (prevents buffer overflow)
    snprintf(buf, sizeof(buf), "Pi is %.2f", 3.14);
    printf("%s\n", buf);

    return 0;
}

String arrays

#include <stdio.h>

int main() {
    // Array of string pointers
    const char *fruits[] = {
        "Apple", "Banana", "Cherry", "Date"
    };
    int count = sizeof(fruits) / sizeof(fruits[0]);

    for (int i = 0; i < count; i++) {
        printf("%s\n", fruits[i]);
    }

    // 2D char array (fixed-size strings)
    char names[3][20] = {
        "Alice", "Bob", "Charlie"
    };

    for (int i = 0; i < 3; i++) {
        printf("Name: %s\n", names[i]);
    }

    return 0;
}

Building strings safely

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

int main() {
    char buffer[100] = "";
    size_t pos = 0;

    // Safe string building with snprintf
    pos += snprintf(buffer + pos, sizeof(buffer) - pos, "Name: %s", "Alice");
    pos += snprintf(buffer + pos, sizeof(buffer) - pos, ", Age: %d", 30);
    pos += snprintf(buffer + pos, sizeof(buffer) - pos, ", Score: %.1f", 95.5);

    printf("%s\n", buffer);
    // Name: Alice, Age: 30, Score: 95.5

    return 0;
}

Common mistakes

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

int main() {
    // MISTAKE 1: Buffer overflow
    char small[5];
    // strcpy(small, "Hello World"); // OVERFLOW!

    // MISTAKE 2: Forgetting null terminator
    char bad[5];
    memcpy(bad, "Hello", 5); // No null terminator!
    // printf("%s\n", bad);   // Undefined behavior

    // MISTAKE 3: Comparing strings with ==
    char a[] = "hello";
    char b[] = "hello";
    // if (a == b) { } // Compares addresses, not content!
    if (strcmp(a, b) == 0) { // Correct way
        printf("Strings are equal\n");
    }

    return 0;
}

Mini Practice

Write C code that:

  1. Reads a line of text and counts vowels and consonants
  2. Reverses a string in place
  3. Tokenizes a CSV line and prints each field
  4. Converts a string to uppercase without modifying the original

Up Next

In the next lesson, you'll learn about Pointers — memory addresses and pointer arithmetic.

Related Topics

Frequently Asked Questions about Strings

What is Strings in C?

Strings is a fundamental concept in C. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Strings?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Strings.

Why is Strings important in C?

Strings is essential for C development. Understanding this concept will help you write better code and solve real-world problems more effectively.