C Programming - Beginner to Brilliance / Arrays and Strings

String Manipulation & Functions

🧠 What are Strings in C?

A string is essentially an array of characters that ends with a special character called the null terminator (\\0).

char name[] = "John"; // Actually stored as: 'J', 'o', 'h', 'n', '\\0'

The \\0 character tells C where the string ends.


πŸ“ Header File for Strings

To perform string operations, you must include the built-in library:

#include <string.h>

This gives you access to all standard string functions like strlen(), strcpy(), etc.


πŸ”§ Commonly Used String Functions

Let’s break down the most important ones with explanation, syntax, examples, and behind-the-scenes memory ideas.

βœ… Why do we use * (pointer) in string-related functions :

πŸ” Reason:

In C, strings are actually arrays of characters, and arrays are passed to functions as pointers. So:

char *str = "Hello";

Here, str is a pointer to the first character of the string.


πŸ“Œ Why is Required in Function Declarations?

When you write a function like:

int strlen(char *str);

You're telling the compiler:

β˜‘οΈ "I'm receiving the address of the first character of a string."

You cannot pass the entire array or string directly by value in C β€” C always passes arrays by reference, and this is done via pointers (*).


🚫 Can We Take String Inputs Directly Without Using Pointers?

No, not in function parameters.

For example:

int strlen(char str[]);   // βœ… Valid, but internally same as char *str

Both of these are functionally identical:

int strlen(char str[]);
int strlen(char *str);

Because str[] decays to *str (a pointer) in function parameters.


1️⃣ strlen() – String Length

πŸ“Œ Purpose: Returns the number of characters in a string, excluding the null terminator \\0.

πŸ“„ Syntax:

int strlen(const char *str);

βœ… Example:

char name[] = "Apple";
int len = strlen(name);  // returns 5

🧠 How it works:

  • Starts at index 0, counts until it finds \\0.


2️⃣ strcpy() – String Copy

πŸ“Œ Purpose: Copies a string from source to destination.

πŸ“„ Syntax:

char *strcpy(char *dest, const char *src);

βœ… Example:

char src[] = "Hello";
char dest[20];

strcpy(dest, src); // dest now contains "Hello"

🧠 Behind the Scenes:

  • Copies each character until \\0.

  • ⚠️ Make sure dest has enough space.


3️⃣ strcat() – String Concatenation

πŸ“Œ Purpose: Appends (joins) one string to the end of another.

πŸ“„ Syntax:

char *strcat(char *dest, const char *src);

βœ… Example:

char a[20] = "Good ";
char b[] = "Morning";

strcat(a, b);  // a becomes "Good Morning"

🧠 It finds the end of a, then starts adding b from there.

⚠️ Important: a must be large enough to hold the combined result.


4️⃣ strcmp() – Compare Strings

πŸ“Œ Purpose: Compares two strings lexicographically (like dictionary order).

πŸ“„ Syntax:

int strcmp(const char *str1, const char *str2);

βœ… Example:

strcmp("apple", "banana");  // returns < 0 (because apple comes before)
strcmp("abc", "abc");       // returns 0
strcmp("zebra", "apple");   // returns > 0

🧠 It compares each character until:

  • They mismatch (and returns the difference),

  • Or both strings end.

❗ Do not use == to compare strings. That only compares addresses, not content.


5️⃣ strrev() – Reverse a String

❗ Not part of standard C. Available in some compilers like Turbo C.

βœ… Example:

char s[20] = "Hello";
strrev(s);   // Now s = "olleH"

You can write your own custom function if needed (see below πŸ‘‡).


6️⃣ strncpy() – Safe String Copy

Similar to strcpy(), but limits the number of characters.

πŸ“„ Syntax:

char *strncpy(char *dest, const char *src, size_t n);

βœ… Example:

char s[] = "World";
char d[10];
strncpy(d, s, 3);  // Only copies "Wor"

7️⃣ strncat() – Safe Concatenation

Same idea as strcat() but with character limit.

strncat(dest, src, n);

8️⃣ strchr() and strrchr() – Character Search

Function

Purpose

strchr()

Finds first occurrence of a char

strrchr()

Finds last occurrence of a char

Example:

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

int main() {
    char str[] = "CodeVeda Platform";
    char ch = 'a';

    // Find first and last occurrence
    char *first = strchr(str, ch);
    char *last = strrchr(str, ch);

    printf("Original string: %s\\n", str);

    if (first != NULL) {
        printf("First '%c' found at index: %ld\\n", ch, first - str);
        printf("Substring from first '%c': %s\\n", ch, first);
    } else {
        printf("Character '%c' not found from start.\\n", ch);
    }

    if (last != NULL) {
        printf("Last '%c' found at index: %ld\\n", ch, last - str);
        printf("Substring from last '%c': %s\\n", ch, last);
    } else {
        printf("Character '%c' not found from end.\\n", ch);
    }

    return 0;
}
Original string: CodeVeda Platform
First 'a' found at index: 6
Substring from first 'a': a Platform
Last 'a' found at index: 14
Substring from last 'a': aform

9️⃣ strstr() – Substring Search

Finds first occurrence of a string inside another string.

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

int main() {
    char text[] = "Hello world";
    char *found = strstr(text, "world");

    printf("Found string: %s\\n", found);

    return 0;
}
Found string: world

πŸ§ͺ Custom String Manipulation Examples

πŸ” Reverse a string (manual)

void reverse(char str[]) {
    int len = strlen(str);
    for(int i = 0; i < len/2; i++) {
        char temp = str[i];
        str[i] = str[len - 1 - i];
        str[len - 1 - i] = temp;
    }
}

πŸ†š Difference Between == and strcmp()

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

if (a == b) {  // FALSE: compares addresses
}

if (strcmp(a, b) == 0) {  // TRUE: compares content
}

🧠 Common String Pitfalls

❌ Mistake

🧠 Explanation

Forgetting \\0 (null terminator)

In C, strings are arrays of characters terminated by \\0. If you forget to add it (especially in manual character arrays), the program keeps reading memory until it randomly hits a \\0, which causes garbage output or crashes. Example: char s[5] = {'H','e','l','l','o'}; β†’ no \\0, unsafe.

Not allocating enough space

If your string doesn’t have space for all characters plus the null terminator, it causes buffer overflows – writing past allocated memory, which can corrupt data or crash the program. Example: char s[5] = "Hello"; β†’ needs 6 bytes (5 for "Hello", 1 for \\0).

Using == to compare strings

== compares addresses, not the actual string content. For string comparison, always use strcmp() or similar functions. Example: if (str1 == str2) checks if both point to the same location, not if the strings are equal.

Not including <string.h>

String functions like strlen(), strcpy(), strcmp() are defined in string.h. If you don’t include it, the compiler might give warnings, assume wrong return types, or error out depending on the settings.


βœ… Summary Table

Function

Purpose

strlen()

Find length

strcpy()

Copy

strcat()

Append

strcmp()

Compare

strrev()

Reverse (non-standard)

strchr()

First char match

strstr()

Substring search