Python · SQL · Web Dev · Java · AI/ML tracks launching soon — your one platform for all of IT
Beginner+100 XP

Unit 03 — Strings

Text is just an array of characters. Learn how computers store words, how to manipulate them in C, and solve the classic string problems that appear in every interview.

60 min March 2026
UNIT 03Prerequisite: Unit 02 — Arrays60 min read

Every piece of text your program ever handles — a name, a password, an email address, a sentence — is a string. And a string is nothing more than an array of characters sitting in memory, one after another, with a special signal at the end that says "stop here."

Because you already understand arrays from Unit 02, strings will feel natural. We just need to learn a few new rules — especially that special signal at the end — and then practise the classic problems that show up in almost every coding interview.

// Section 1

What is a String?

In C, a string is an array of char values — where each character is stored as a number according to the ASCII table. The letter 'A' is stored as 65. 'a' is 97. '0' is 48. Your computer never stores letters — only numbers.

// The string "HELLO" in memory — what C actually stores
H
72
[0]
E
69
[1]
L
76
[2]
L
76
[3]
O
79
[4]
\0
0
[5]
visible characters
null terminator \0 — marks end of string

The Null Terminator — the most important rule in C strings

Every string in C ends with a special character called the null terminator, written as '\0'. Its ASCII value is 0. It is not a space — it is a completely invisible marker that tells every string function "the string ends here, stop reading."

⚠️ Important
Critical rule: When you declare a char array to hold a string of n characters, you must declare it with size n+1 — the extra slot is for the null terminator. A string "HELLO" has 5 characters but needs a char array of size 6. Forgetting this causes some of the nastiest bugs in C.
// Section 2

Strings in C — Declaration and Input

Let us see how to create, read, and print strings in C — with every detail explained.

c
#include <stdio.h>
int main() {
/* Method 1: initialise directly — added automatically */
char name[6] = "HELLO"; /* size 6 = 5 chars + 1 for \0 */
/* Method 2: character by character — must add \0 yourself */
char city[7];
city[0] = 'M';
city[1] = 'U';
city[2] = 'M';
city[3] = 'B';
city[4] = 'A';
city[5] = 'I';
city[6] = '\0'; /* MUST add this — or the string has no end */
/* Method 3: let C count the size */
char lang[] = "Python"; /* compiler sets size to 7 automatically */
printf("Name: %s\n", name); /* %s prints a string */
printf("City: %s\n", city);
printf("Lang: %s\n", lang);
return 0;
}

Reading a string from the user

c
#include <stdio.h>
int main() {
char name[50]; /* enough space for the input */
printf("Enter your name: ");
scanf("%s", name); /* no & needed — array name IS already an address */
printf("Hello, %s!\n", name);
return 0;
}
⚠️ Important
Important: scanf("%s") stops reading at a space. So "Asil Khan" would only store "Asil". To read a full line including spaces, use fgets(name, 50, stdin) instead. We will use this in the examples below.
// Section 3

Built-in String Functions in C

C gives you a library called string.h with ready-made functions for common string operations. You include it the same way as stdio.h. Knowing these saves you from writing everything from scratch.

FunctionWhat it doesExampleReturns
strlen(s)Count characters (not including \0)strlen("HELLO")5
strcpy(dest, src)Copy src into deststrcpy(a, "Hi")void
strcat(dest, src)Append src to end of deststrcat(a, " World")void
strcmp(s1, s2)Compare two stringsstrcmp("abc", "abc")0 if equal
strchr(s, c)Find first occurrence of char cstrchr("hello", 'l')pointer or NULL
strstr(s1, s2)Find s2 inside s1strstr("hello world", "world")pointer or NULL
strupr(s)Convert to uppercasestrupr("hello")"HELLO"
strlwr(s)Convert to lowercasestrlwr("HELLO")"hello"
c
#include <stdio.h>
#include <string.h> /* required for all string functions */
int main() {
char s1[20] = "Hello";
char s2[] = " World";
printf("Length: %lu\n", strlen(s1)); /* Length: 5 */
strcat(s1, s2); /* s1 becomes "Hello World" */
printf("After strcat: %s\n", s1);
printf("Compare: %d\n", strcmp("abc", "abc")); /* 0 — equal */
printf("Compare: %d\n", strcmp("abc", "abd")); /* negative — abc comes before abd */
return 0;
}
💡 Note
strcmp returns: 0 if both strings are identical, a negative number if s1 comes before s2 alphabetically, and a positive number if s1 comes after s2. Never use == to compare strings in C — it compares addresses, not content.
// Section 4

Traversing a String — Character by Character

Since a string is an array, you can loop through it just like any array. The trick is knowing when to stop — and the answer is the null terminator. When you hit '\0', you stop.

c
#include <stdio.h>
int main() {
char str[] = "Chaduvuko";
int i = 0;
/* Method 1: use strlen to get the count */
for (i = 0; str[i] != '\0'; i++) { /* stop when you hit the null terminator */
printf("%c ", str[i]);
}
printf("\n");
/* Output: C h a d u v u k o */
/* Method 2: count uppercase and lowercase letters */
int upper = 0, lower = 0;
for (i = 0; str[i] != '\0'; i++) {
if (str[i] >= 'A' && str[i] <= 'Z') {
upper++; /* ASCII range for uppercase: 65 to 90 */
} else if (str[i] >= 'a' && str[i] <= 'z') {
lower++; /* ASCII range for lowercase: 97 to 122 */
}
}
printf("Uppercase: %d, Lowercase: %d\n", upper, lower);
/* Output: Uppercase: 1, Lowercase: 8 */
return 0;
}
// Section 5

Classic String Problems — With Full Solutions

These are the exact problems that appear in every beginner and intermediate coding interview. Understand the logic — not just the code.

Problem 01Reverse a StringO(n)

Same two-pointer technique as reversing an array from Unit 02. One pointer at the start, one at the end — swap and move inward until they meet.

c
#include <stdio.h>
#include <string.h>
void reverseString(char str[]) {
int left = 0;
int right = strlen(str) - 1; /* index of last character (before \0) */
char temp;
while (left < right) {
temp = str[left]; /* swap characters */
str[left] = str[right];
str[right] = temp;
left++;
right--;
}
}
int main() {
char str[] = "Chaduvuko";
printf("Before: %s\n", str); /* Chaduvuko */
reverseString(str);
printf("After: %s\n", str); /* okuvadhC */
return 0;
}
Problem 02Check if a String is a PalindromeO(n)

A palindrome reads the same forwards and backwards — "madam", "racecar", "level". Compare characters from both ends — if any pair doesn't match, it's not a palindrome.

c
#include <stdio.h>
#include <string.h>
int isPalindrome(char str[]) {
int left = 0;
int right = strlen(str) - 1;
while (left < right) {
if (str[left] != str[right]) {
return 0; /* mismatch found — not a palindrome */
}
left++;
right--;
}
return 1; /* all pairs matched — it is a palindrome */
}
int main() {
char s1[] = "madam";
char s2[] = "hello";
if (isPalindrome(s1)) {
printf("%s is a palindrome\n", s1); /* madam is a palindrome */
}
if (!isPalindrome(s2)) {
printf("%s is NOT a palindrome\n", s2); /* hello is NOT a palindrome */
}
return 0;
}
Problem 03Count Vowels and ConsonantsO(n)

Walk through each character. If it is a, e, i, o, u (uppercase or lowercase) it is a vowel. If it is any other letter it is a consonant. Spaces and digits are neither.

c
#include <stdio.h>
int main() {
char str[] = "Chaduvuko Platform";
int vowels = 0, consonants = 0;
int i;
for (i = 0; str[i] != '\0'; i++) {
char c = str[i];
/* convert to lowercase for easier checking */
if (c >= 'A' && c <= 'Z') {
c = c + 32; /* ASCII trick: 'A'(65) + 32 = 'a'(97) */
}
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowels++;
} else if (c >= 'a' && c <= 'z') {
consonants++; /* it is a letter but not a vowel */
}
/* spaces, digits, symbols — ignored */
}
printf("Vowels: %d\n", vowels); /* Vowels: 7 */
printf("Consonants: %d\n", consonants); /* Consonants: 10 */
return 0;
}
Problem 04Check if Two Strings are AnagramsO(n)

Two strings are anagrams if they contain the exact same characters in any order. "listen" and "silent" are anagrams. The approach: count how many times each letter appears in string 1, then subtract for string 2. If all counts reach zero — anagram.

c
#include <stdio.h>
#include <string.h>
int isAnagram(char s1[], char s2[]) {
/* first check: if lengths differ they cannot be anagrams */
if (strlen(s1) != strlen(s2)) {
return 0;
}
int freq[26] = {0}; /* one slot for each letter a-z, all start at 0 */
int i;
/* count up for every character in s1 */
for (i = 0; s1[i] != '\0'; i++) {
freq[s1[i] - 'a']++; /* 'a'-'a'=0, 'b'-'a'=1, 'c'-'a'=2 ... */
}
/* count down for every character in s2 */
for (i = 0; s2[i] != '\0'; i++) {
freq[s2[i] - 'a']--;
}
/* if any count is non-zero, the strings are not anagrams */
for (i = 0; i < 26; i++) {
if (freq[i] != 0) {
return 0;
}
}
return 1; /* all counts are zero — anagram confirmed */
}
int main() {
char s1[] = "listen";
char s2[] = "silent";
if (isAnagram(s1, s2)) {
printf("'%s' and '%s' ARE anagrams\n", s1, s2); /* ARE anagrams */
} else {
printf("NOT anagrams\n");
}
return 0;
}
🎯 Pro Tip
The freq[s1[i] - 'a'] trick is something you will use constantly in string problems. Since 'a' = 97 in ASCII, subtracting 'a' from any lowercase letter gives its position: 'a' - 'a' = 0, 'b' - 'a' = 1, 'z' - 'a' = 25. This maps any letter to an array index cleanly.
Problem 05Count Words in a SentenceO(n)

A new word starts when you see a non-space character after a space (or at the very beginning). Track whether the previous character was a space — that is all you need.

c
#include <stdio.h>
int countWords(char str[]) {
int count = 0;
int inWord = 0; /* flag: are we currently inside a word? */
int i;
for (i = 0; str[i] != '\0'; i++) {
if (str[i] != ' ' && inWord == 0) {
inWord = 1; /* just entered a new word */
count++;
} else if (str[i] == ' ') {
inWord = 0; /* just left a word */
}
}
return count;
}
int main() {
char sentence[] = "Learn DSA on Chaduvuko";
printf("Word count: %d\n", countWords(sentence)); /* Word count: 4 */
return 0;
}
Problem 06Replace All Occurrences of a CharacterO(n)

Walk through the string once. Every time you find the target character, replace it. Single pass — O(n).

c
#include <stdio.h>
void replaceChar(char str[], char find, char replace) {
int i;
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == find) {
str[i] = replace;
}
}
}
int main() {
char str[] = "data engineering";
printf("Before: %s\n", str); /* data engineering */
replaceChar(str, 'a', '@');
printf("After: %s\n", str); /* d@t@ engineering */
return 0;
}
// Errors You Will Hit

Real Mistakes — And Exactly How to Fix Them

These are the three string mistakes that trip up almost every C beginner. Read them now so you do not waste hours debugging them later.

Forgetting the null terminator
Symptom: Your string prints garbage characters after the real content — like "hello@#%&"
Fix: Always declare char arrays with size n+1. Always end manually built strings with '\0'.
char name[5] = "Hello"; /* WRONG — no room for \0 */ char name[6] = "Hello"; /* CORRECT — 5 chars + 1 for \0 */
Using == to compare strings
Symptom: Your if condition always returns false even when strings look identical
Fix: Use strcmp(s1, s2) == 0 to compare. The == operator compares memory addresses, not content.
if (s1 == s2) { } /* WRONG — compares addresses */ if (strcmp(s1, s2) == 0) { } /* CORRECT — compares content */
Buffer overflow — writing past the array end
Symptom: Program crashes or corrupts other variables unexpectedly
Fix: Always make sure your destination array is large enough before strcpy or strcat. Check lengths first.
char dest[5]; strcpy(dest, "Hello World"); /* WRONG — "Hello World" needs 12 bytes */ char dest[12]; strcpy(dest, "Hello World"); /* CORRECT */
// Section 6

Quick Reference — Operations Summary

OperationMethodTimeKey point
Get lengthstrlen(s)O(n)Walks to \0 — not O(1)
Copy stringstrcpy(dest, src)O(n)dest must be large enough
Concatenatestrcat(dest, src)O(n)dest must have room for both
Comparestrcmp(s1, s2)O(n)Returns 0 if equal
ReverseTwo pointer swapO(n)Works in-place, O(1) space
Palindrome checkTwo pointer compareO(n)Stop at first mismatch
Anagram checkFrequency arrayO(n)26-slot int array for a–z
TraverseLoop until \0O(n)Use != '\0' as stop condition
// What's Next

You Are Ready for Unit 04

You now understand strings fully — how they sit in memory, how to manipulate them, and how to solve the classic problems. You have also seen the frequency array trick which appears constantly in string, array, and hashing problems.

In Unit 04 we tackle Pointers — the concept that confuses most beginners but is the backbone of everything advanced in C. You have already seen pointers briefly with the & in scanf and with array names being addresses. Now we make it all explicit and clear.

UP NEXT → UNIT 04
Pointers — The Concept That Changes Everything
Memory addresses, & and *, pointer arithmetic — explained simply.
Coming Soon →

🎯 Key Takeaways

  • A string in C is a char array that ends with a null terminator \0 — without it, the string has no end
  • Always declare char arrays with size n+1 — the extra slot is for \0
  • Use %s to print strings, strlen() to get length, strcpy() to copy, strcat() to join, strcmp() to compare
  • Never use == to compare strings — use strcmp(s1, s2) == 0
  • Traverse a string with a loop that stops when it hits \0, not when it hits a fixed size
  • The frequency array trick (int freq[26]) is the key to solving anagram, duplicate, and counting problems
  • The two-pointer technique from arrays works perfectly for reversing strings and palindrome checks
  • Lowercase letter to array index: use char - 'a' (e.g. 'c' - 'a' = 2)
Share

Discussion

0

Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.

Continue with GitHub
Loading...