Strings in C

In C, a string is a sequence of characters stored in an array of type char, terminated by a special null character '\0' (also written as \0). Unlike languages like Python or Java that have a built-in string data type, C represents strings as character arrays.

The null character '\0' marks the end of the string. It is added automatically when a string literal is used, but must be kept in mind when working manually with character arrays.

Declaring and Initializing Strings

Method 1 — Using a String Literal


char name[10] = "Alice";
// Internally stored as: A l i c e \0 (6 characters, 10 reserved)

Method 2 — Character by Character


char name[6] = {'A', 'l', 'i', 'c', 'e', '\0'};
// Must include \0 manually!

Method 3 — Without Size (Auto-sized)


char greeting[] = "Hello";
// Compiler allocates 6 bytes: H e l l o \0

Visualizing String Storage


char name[] = "Alice";

Index:  0    1    2    3    4    5
Value: 'A'  'l'  'i'  'c'  'e'  '\0'

Printing a String


#include <stdio.h>

int main()
{
    char name[] = "Alice";
    char city[] = "Delhi";

    printf("Name: %s\n", name);  // %s is used for strings
    printf("City: %s\n", city);

    return 0;
}

Output


Name: Alice
City: Delhi

Reading a String from User

Using scanf() — Reads One Word (No Spaces)


#include <stdio.h>

int main()
{
    char username[50];

    printf("Enter username: ");
    scanf("%s", username);  // no & needed for arrays

    printf("Hello, %s!\n", username);

    return 0;
}

Using fgets() — Reads Full Line (Including Spaces)


#include <stdio.h>

int main()
{
    char fullName[100];

    printf("Enter full name: ");
    fgets(fullName, 100, stdin);

    printf("Hello, %s", fullName);

    return 0;
}

Sample Interaction


Enter full name: Alice Johnson
Hello, Alice Johnson

String Library Functions — <string.h>

The <string.h> header file provides a rich set of built-in functions for working with strings. Always include it when using these functions.

1. strlen() — String Length

Returns the number of characters in a string, not including the null character.


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

int main()
{
    char word[] = "Programming";
    printf("Length: %zu\n", strlen(word));  // Output: 11
    return 0;
}

2. strcpy() — String Copy

Copies the content of one string into another.


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

int main()
{
    char source[] = "Hello";
    char destination[20];

    strcpy(destination, source);  // copies source into destination

    printf("Destination: %s\n", destination);  // Hello

    return 0;
}

3. strcat() — String Concatenation (Joining)

Appends (joins) one string to the end of another.


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

int main()
{
    char first[30] = "Hello";
    char second[] = ", World!";

    strcat(first, second);  // first = "Hello, World!"

    printf("%s\n", first);  // Hello, World!

    return 0;
}

4. strcmp() — String Comparison

Compares two strings character by character. Returns:

  • 0 — if both strings are equal
  • Positive value — if the first string is greater
  • Negative value — if the first string is smaller

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

int main()
{
    char pass1[] = "secret";
    char pass2[] = "secret";
    char pass3[] = "wrong";

    if (strcmp(pass1, pass2) == 0)
        printf("Passwords match!\n");
    else
        printf("Passwords do not match.\n");

    if (strcmp(pass1, pass3) != 0)
        printf("Second comparison: Not equal.\n");

    return 0;
}

Output


Passwords match!
Second comparison: Not equal.

5. strcmpi() / strcasecmp() — Case-Insensitive Comparison

Compares strings ignoring case (uppercase/lowercase). Use strcmpi() on Windows (MSVC) or strcasecmp() on Linux/macOS.


// Linux / macOS
if (strcasecmp("Hello", "hello") == 0)
    printf("Equal (case insensitive)\n");

6. strrev() — Reverse a String

strrev() is available in some compilers (like MSVC on Windows) but not ANSI standard. Below is a manual reversal:


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

int main()
{
    char word[] = "hello";
    int len = strlen(word);
    int i, j;
    char temp;

    for (i = 0, j = len - 1; i < j; i++, j--)
    {
        temp = word[i];
        word[i] = word[j];
        word[j] = temp;
    }

    printf("Reversed: %s\n", word);  // olleh

    return 0;
}

7. strupr() and strlwr() — Convert Case

Available in MSVC on Windows. Below is a manual approach using <ctype.h>:


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

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

    // Convert to uppercase
    for (int i = 0; word[i]; i++)
        word[i] = toupper(word[i]);
    printf("Uppercase: %s\n", word);  // HELLO WORLD

    // Convert to lowercase
    for (int i = 0; word[i]; i++)
        word[i] = tolower(word[i]);
    printf("Lowercase: %s\n", word);  // hello world

    return 0;
}

8. strstr() — Find Substring

Searches for a substring within a string. Returns a pointer to the first occurrence, or NULL if not found.


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

int main()
{
    char sentence[] = "C programming is fun";
    char search[] = "programming";

    if (strstr(sentence, search) != NULL)
        printf("'%s' found in the sentence.\n", search);
    else
        printf("Not found.\n");

    return 0;
}

Output


'programming' found in the sentence.

Summary of Common String Functions

FunctionHeaderPurpose
strlen(s)string.hReturns length of string s
strcpy(d, s)string.hCopies string s into d
strcat(d, s)string.hAppends s to end of d
strcmp(s1, s2)string.hCompares two strings
strstr(s, sub)string.hFinds substring in string
toupper(c)ctype.hConverts char to uppercase
tolower(c)ctype.hConverts char to lowercase
isalpha(c)ctype.hChecks if char is a letter
isdigit(c)ctype.hChecks if char is a digit

Traversing a String Character by Character


#include <stdio.h>

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

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

    return 0;
}

Output


H
e
l
l
o

Count Vowels in a String


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

int main()
{
    char sentence[100];
    int vowels = 0;

    printf("Enter a sentence: ");
    fgets(sentence, 100, stdin);

    for (int i = 0; sentence[i] != '\0'; i++)
    {
        char c = tolower(sentence[i]);
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
            vowels++;
    }

    printf("Number of vowels: %d\n", vowels);

    return 0;
}

Summary

Strings in C are character arrays terminated by a null character '\0'. They are handled through the <string.h> and <ctype.h> libraries. Key operations include finding length, copying, concatenating, and comparing strings. Since C does not have a built-in string type, understanding how strings work as character arrays is a fundamental skill for any C programmer. Always ensure the array is large enough to hold the string plus the null terminator.

Leave a Comment

Your email address will not be published. Required fields are marked *