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.

Comments

Popular posts from this blog

Programming For Problem Solving

What are General Problem-Solving Concepts? Problem-solving is an important skill at both the personal and professional levels. People make decisions to solve a problem. Whether you’re fixing a leaking faucet at home or troubleshooting complex technical issues on a computer, the ability to effectively troubleshoot challenges is invaluable. In this comprehensive tutorial, we’ll delve into the troubleshooting mindset, general availability, and its practical applications in the computer industry. By breaking down the process into manageable steps and providing technical examples, we aim to equip readers with the tools to solve problems practically and confidently. Total Steps for Problem Solving: 1. Identifying the Problem The fundamental principle of problem-solving lies in accurately identifying the issue at hand. This involves understanding the signs and figuring out what's causing the problem. Consider a scenario where your computer suddenly c...

Magic of Algorithms: The Heartbeat of Computer Science and Problem-Solving

What is an Algorithm? Introduction: In the world of computers and technology, algorithms play a huge role, kind of like the conductor of an orchestra, guiding every instrument to make beautiful music. But what exactly are algorithms, and why are they so important, especially when it comes to solving problems? Definition: Algorithms are step-by-step procedures designed to solve problems, accomplish tasks, or achieve specific objectives within a finite number of operations. They serve as the fundamental building blocks upon which the vast edifice of computer science rests, wielding the power to transform abstract concepts into tangible solutions. Algorithms are the backbone of computer science, making it possible for computers to do all the amazing things they do. Note: Click on the image for a clear view. ➔ Read more about problem solving Importance of Algorithms in Computer Science: Whether it's optimizing search engine al...