Skip to main content

Strings in C

C Programming: Working with Strings

Unlike modern programming languages like Python or Java, C does not possess a dedicated "String" data type. Instead, C treats a string as a simple 1D array of characters.

Real-life example: Think of a freight train. The train does not exist as one solid object; it consists of individual boxcars linked together. Similarly, a C string links individual characters side-by-side in memory. To let the computer know the train has ended, C attaches a special "caboose" called the Null Terminator (\0).

1. Essential String Functions

Handling strings manually requires complex loops. To save time, C provides a built-in library called <string.h> that contains powerful functions to manipulate text.

  • strlen(): You use this to find the exact length of a string. The compiler counts the characters until it hits the \0 terminator. It does not count the terminator itself.
  • strcpy(): You use this to copy the contents of one string directly into another. It overwrites whatever previously existed in the destination string.
  • strcmp(): You use this to compare two strings lexicographically (alphabetical order). If the two strings match perfectly, the function returns a 0. If they differ, it returns a positive or negative number based on their ASCII differences.
  • strcat(): You use this to concatenate (link) two strings. The function takes the second string and seamlessly attaches it to the very end of the first string, effectively combining them.

2. Problem Solving Focus: String Algorithms

To master strings, you must understand how to navigate them character by character. Here are five classic string manipulation algorithms that you will encounter in coding interviews.

Problem 1: Reverse a String

We use the Two-Pointer technique. We place one pointer at the first character and one at the last valid character (right before the \0). We swap them and move inward.

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

int main() {
    char str[] = "Programming";
    int start = 0;
    int end = strlen(str) - 1;
    char temp;

    while(start < end) {
        // Swap the characters
        temp = str[start];
        str[start] = str[end];
        str[end] = temp;

        start++;
        end--;
    }

    printf("Reversed String: %s\n", str);
    return 0;
}

Problem 2: Palindrome String Checker

A palindrome reads the exact same forwards and backwards (like "madam"). We use two pointers again. If at any point the left character does not match the right character, the word fails the test instantly.

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

int main() {
    char str[] = "racecar";
    int start = 0;
    int end = strlen(str) - 1;
    int isPalindrome = 1; // Assume true initially

    while(start < end) {
        if(str[start] != str[end]) {
            isPalindrome = 0; // Mismatch found!
            break;
        }
        start++;
        end--;
    }

    if(isPalindrome)
        printf("The string is a Palindrome.\n");
    else
        printf("The string is NOT a Palindrome.\n");
    return 0;
}

Problem 3: Count Characters (Without strlen)

In interviews, companies frequently ask you to calculate the length of a string without using the built-in strlen() function. We solve this by looping through the array until we crash into the Null Terminator.

#include <stdio.h>

int main() {
    char str[] = "Hello World";
    int count = 0;

    // Keep looping until we hit the \0 character
    while(str[count] != '\0') {
        count++;
    }

    printf("Total characters: %d\n", count);
    return 0;
}

Problem 4: Remove Duplicates from a String

To eliminate duplicates cleanly, we use a Hash Array (or frequency tracker) of size 256 to cover all possible ASCII characters. As we read the string, we mark characters we have seen. If we encounter a marked character again, we simply skip it.

#include <stdio.h>

int main() {
    char str[] = "programming";
    int hash[256] = {0}; // Array to track seen characters
    int currentIndex = 0;

    for(int i = 0; str[i] != '\0'; i++) {
        // If we have not seen this character yet
        if(hash[(unsigned char)str[i]] == 0) {
            hash[(unsigned char)str[i]] = 1; // Mark it as seen
            str[currentIndex++] = str[i]; // Overwrite the string in place
        }
    }

    // Terminate the new, shorter string
    str[currentIndex] = '\0';
    
    printf("String after removing duplicates: %s\n", str);
    return 0;
}

Problem 5: Verify an Anagram

Two strings are anagrams if they use the exact same characters in the exact same quantities (like "listen" and "silent"). We build a single frequency array. We increment the count for every character in the first word, and decrement the count for every character in the second word. If the final array contains all zeros, they are a perfect match.

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

int main() {
    char str1[] = "listen";
    char str2[] = "silent";
    int count[256] = {0};
    int isAnagram = 1;

    // If lengths differ, they physically cannot be anagrams
    if(strlen(str1) != strlen(str2)) {
        isAnagram = 0;
    } else {
        // Add frequencies from str1, subtract from str2
        for(int i = 0; str1[i] != '\0'; i++) {
            count[(unsigned char)str1[i]]++;
            count[(unsigned char)str2[i]]--;
        }
        
        // Verify all buckets returned to exactly zero
        for(int i = 0; i < 256; i++) {
            if(count[i] != 0) {
                isAnagram = 0;
                break;
            }
        }
    }

    if(isAnagram)
        printf("The strings ARE anagrams.\n");
    else
        printf("The strings are NOT anagrams.\n");
    return 0;
}


Click on img to view 

Summary: Strings

  • C does not have a dedicated string data type; it simply utilizes an array of characters.
  • Every valid C string must end with a Null Terminator (\0).
  • Programmers use the <string.h> library to quickly copy, compare, and concatenate text without writing manual loops.
  • You can efficiently track and manipulate string data using an ASCII frequency array of size 256.

C Programming Interview Questions (FAQs)

1. Why must strings end with a '\0' (Null Terminator)?

Unlike other languages, C arrays do not automatically remember their own size. When you pass a string to a function like printf(), the computer has no idea where your text ends and where random memory garbage begins. The Null Terminator acts as a physical stop sign. The compiler reads characters one by one and instantly stops processing the moment it hits the \0.

2. What is the difference between char[] and char*?

When you write char arr[] = "Hello";, the compiler creates a fresh, mutable array in your local stack memory and copies the word "Hello" into it. You can modify any letter in this array. However, when you write char *str = "Hello";, the compiler creates a pointer that points to a "string literal" stored in the Read-Only Data Segment of the RAM. If you attempt to alter a letter in the char* version, the operating system instantly crashes your program with a Segmentation Fault.

➔ Read more about Data Types ➔ Read more about Fundamentals ➔ Read more about Variables and Storage Classes ➔ Read more about String ➔ Read more about Operators ➔ Read more about Control Statements and Loops in C ➔ Read more about Functions ➔ Read more about Arrays ➔ Read more about Pointers ➔ Read more about Structures ➔ Read more about Enum ➔ Read more about Union

Comments

Popular posts from this blog

How I Got Selected in MNC

Virtusa Sometimes success does not come from having the best coding skills or the perfect roadmap. Sometimes it comes from simply refusing to quit. This is the honest story of how I transitioned from a confused, rejected fresher to getting selected as an Associate Engineer at Virtusa. The Beginning: Confused About My Future After completing my graduation, I stared blankly at my career options. Like many freshers, I lacked a clear direction. Should I join a Java course? Should I prepare on my own? Should I just wait for campus placement opportunities? One day, I called my friend Chetan. He suggested I join Naresh i Technologies and start learning Java seriously. Still unsure of my path, I told him I needed time to think about it. A couple of days later, my phone buzzed with a WhatsApp message offering a job opportunity. They asked me to come for the next round of the recruitment process. Excitement completely took over. I packed my bags, traveled to th...

Spring Boot Introduction

Spring Boot Introduction: Architecture, Dependencies, and Embedded Servers Modern enterprise applications demand rapid development, frictionless deployment, and absolute minimal configuration. Before Spring Boot arrived, developers utilizing the Spring Framework wasted immense amounts of time configuring XML files, managing clashing dependencies, setting up clunky application servers, and stitching various Spring modules together manually. To eliminate these bottlenecks, Pivotal introduced Spring Boot . Built entirely on top of the traditional Spring Framework, Spring Boot is an "opinionated" framework. It aggressively simplifies application development by injecting auto-configuration, packaging starter dependencies, and embedding web servers directly into your application. This allows backend developers to focus entirely on building business logic rather than wrestling with infrastructure setup. What is Spring Boot? Spring Boot is a powerful extens...

Data Types in C

C Programming: Understanding Data Types Think of your kitchen. You store a large bag of flour in a big bin, a pinch of saffron in a tiny jar, and milk in a liquid measuring jug. You do not put liquids into paper bags, and you do not use a massive bucket for a single teaspoon of sugar. C programming works the exact same way. When you create a variable, you must tell the computer exactly what kind of "container" to build in its memory. We call these containers Data Types . They dictate what kind of data the container holds, how much space it takes up, and what operations you can perform on it. 1. Primitive Data Types C offers several built-in, "primitive" data types. Think of these as the fundamental storage containers. int (Integer): You use this to store whole numbers without decimals. Real-life example: Counting the number of people in a room or tracking a player's score in a video game. char (Character): You use this ...