DSA SERIES Chapter 3 STRINGS (In C)

[Follow here] for daily coding insights.

DSA SERIES

Topic 3: STRINGS (In C)



1. What is a String in C?

In C, a string is an array of characters, terminated by a NULL character ‘\0’.

Example:

char name[] = "Hello";

Stored as:
H e l l o \0

This null character marks the end of the string.


2. Memory Representation of Strings (Very Important)

Case 1:

char s[] = "ABC";

Creates:
A | B | C | \0
Total size = 4 bytes.

Case 2:

char *p = "ABC";
  • Stored in read-only memory (string literal area).

  • p → pointer to constant characters.

  • Modifying it causes undefined behavior.


3. String Declaration Methods

✔ Method 1 — Character Array (modifiable)

char str[10] = "India";

✔ Method 2 — Character Array (manual termination)

char str[] = {'I','n','d','i','a','\0'};

✔ Method 3 — Pointer to string literal (NOT modifiable)

char *str = "India";

4. Input & Output of Strings

Using scanf()

scanf("%s", str);

❌ But stops at space
Input: New Delhi
Stored: New

Using gets()

gets() is removed due to buffer overflow issues.

Using fgets() — safest method

fgets(str, sizeof(str), stdin);

5. Operations on Strings

5.1 String Length (strlen)

int len = strlen(str);

5.2 String Copy (strcpy)

strcpy(dest, src);

5.3 String Concatenation (strcat)

strcat(s1, s2);

5.4 String Comparison (strcmp)

if(strcmp(a, b) == 0)
    printf("Equal");

5.5 Custom Implementations (Very Important for DSA)

Interviewers expect manual implementations.

Implement strlen()

int my_strlen(const char *s) {
    int len = 0;
    while(s[len] != '\0')
        len++;
    return len;
}

Implement strcpy()

void my_strcpy(char *dest, const char *src) {
    int i = 0;
    while(src[i] != '\0') {
        dest[i] = src[i];
        i++;
    }
    dest[i] = '\0';
}

Implement strcmp()

int my_strcmp(const char *s1, const char *s2) {
    int i = 0;
    while(s1[i] != '\0' && s2[i] != '\0') {
        if(s1[i] != s2[i])
            return s1[i] - s2[i];
        i++;
    }
    return s1[i] - s2[i];
}

6. Important Points About Strings in C

  •  Strings are mutable only when stored in character arrays.
  •  char *s = "ABC" cannot be modified.
  •  Always ensure enough memory for \0.
  •  Avoid gets() — overflow risk.
  •  strcpy/strcat must be used with caution (risk of overflow).
  •  Prefer fgets() and strncpy() for safer operations.


7. Common Interview Mistakes

X Forgetting \0

char str[3] = "ABC"; // Wrong (needs 4 bytes)

X Modifying string literal

char *s = "Hello";
s[0] = 'Y';  // Undefined behavior

X Not allocating enough memory before strcat()

char a[5] = "Hi";
char b[] = "All";
strcat(a, b); // Overflow (a can hold only 5 chars)

8. Real DSA-Level String Problems in C (with logic)

1) Reverse a string

Logic: Two-pointer swapping until indices meet.

2) Check if a string is palindrome

Logic: Compare characters from start and end.

3) Count vowels, consonants, digits, spaces

Logic: ASCII checking.

4) Find frequency of each character

Logic: Use an int freq[256] array.

5) Remove duplicates

Logic: Mark visited characters using a boolean array.

Full implementations will be given if you want.


9. 20 Practice Questions (C Edition)

Questions

  1. What is a string in C?

  2. Why is '\0' needed?

  3. Difference between char array and char pointer?

  4. Write a program to find length of string without strlen().

  5. Write code to copy one string to another without strcpy().

  6. Why is gets() unsafe?

  7. How does fgets() work?

  8. How to safely read a multi-word string?

  9. Write a program to reverse a string.

  10. What is string literal?

  11. Can you modify a string literal?

  12. Explain memory layout of "HELLO".

  13. Write logic to compare two strings without strcmp().

  14. What will be size of char s[] = "ABCD";?

  15. What is difference between strlen() and sizeof()?

  16. Write code to count vowels.

  17. Write code to check palindrome.

  18. What is the use of <string.h>?

  19. How to concatenate strings without strcat()?

  20. Explain buffer overflow in strings.


Answers

  1. Char array ending with '\0'.

  2. To mark end of string.

  3. Array is modifiable; pointer may not be.

  4. Loop until '\0'.

  5. Copy characters until '\0'.

  6. It causes buffer overflow.

  7. Reads string including spaces; stops at newline or size-1.

  8. Using fgets().

  9. Two-pointer swap logic.

  10. A constant string stored in read-only memory.

  11. No (undefined behavior).

  12. Each character + '\0' stored sequentially.

  13. Compare characters one by one.

  14. 5 bytes (4 chars + '\0').

  15. strlen counts characters; sizeof gives total memory.

  16. Check each char and count vowels.

  17. Compare from both ends.

  18. Provides string functions.

  19. Append manually with loop.

  20. Writing beyond allocated memory.

ALSO CHECK 

DS(Data Structure) Python&C Edition

DSA Series Chapter 1 Time & Space Complexity ( C Edition)

DSA Series Chapter 2 Arrays  (C Version)







Tail Recursion Optimization: How Compilers Convert Recursion Into Iteration


Advanced Recursion: Memoization vs. Tabulation — The Deep Optimization Blueprint for Professionals


Advanced Sorting Algorithms: Merge Sort Internals — Merge Tree, Cache Behavior & Real Cost Analysis


Enjoyed this post? [Follow here] for daily coding insights.

Comments