String Operations Without string.h
"Find the length of a string without using strlen." "Reverse a string without strrev." Examiners and interviewers love these questions, because they show whether you really understand how strings work.
In this lesson you will write your own versions of the common string functions, plus reverse and palindrome programs. The secret behind all of them is one idea: walk the array until '\0'.
What You Will Learn
- How to find the length of a string without
strlen. - How to copy and join strings without
strcpy/strcat. - How to compare strings without
strcmp. - How to reverse a string in place.
- How to check if a string is a palindrome.
String Operations Without Library Functions Explained
Exam definition: String operations without library functions are done by processing the character array directly with loops: moving an index from 0 until the null character '\0' is reached, and writing '\0' at the end of every new string you build.
Memory trick: Every string program has two rules: "Walk till \0" and "End with \0". Reading? Stop at '\0'. Writing? Put '\0' at the end.
The two patterns
READ pattern WRITE pattern
i = 0 i = 0
while s[i] != '\0': while src[i] != '\0':
use s[i] dest[i] = src[i]
i++ i++
dest[i] = '\0' <- never forget
Example 1: Length, Copy, Concatenate and Compare Without string.h
#include <stdio.h>
int my_strlen(const char s[])
{
int i = 0;
while (s[i] != '\0')
i++;
return i;
}
void my_strcpy(char dest[], const char src[])
{
int i = 0;
while (src[i] != '\0')
{
dest[i] = src[i];
i++;
}
dest[i] = '\0';
}
void my_strcat(char dest[], const char src[])
{
int i = my_strlen(dest); /* start writing at dest's '\0' */
int j = 0;
while (src[j] != '\0')
{
dest[i] = src[j];
i++;
j++;
}
dest[i] = '\0';
}
int my_strcmp(const char a[], const char b[])
{
int i = 0;
while (a[i] != '\0' && a[i] == b[i])
i++;
return a[i] - b[i]; /* 0 if equal */
}
int main(void)
{
char s1[40] = "Study";
char s2[] = "Fame";
char copy[40];
printf("Length of \"%s\" = %d\n", s1, my_strlen(s1));
my_strcpy(copy, s1);
printf("Copy = %s\n", copy);
my_strcat(s1, s2);
printf("Joined = %s\n", s1);
printf("Compare(\"abc\", \"abc\") = %d\n", my_strcmp("abc", "abc"));
printf("Compare(\"abc\", \"abd\") = %d\n", my_strcmp("abc", "abd"));
return 0;
}
Output
Length of "Study" = 5
Copy = Study
Joined = StudyFame
Compare("abc", "abc") = 0
Compare("abc", "abd") = -1
Code Explanation
- my_strlen: moves
iforward untils[i]is'\0'. The finaliis the length. - my_strcpy: copies each character, then writes
'\0'at the end. Without that last line,destwould not be a valid string. - my_strcat: starts writing at index
my_strlen(dest), which is where dest's old'\0'was. It overwrites that'\0'and adds a new one at the end. - my_strcmp: skips equal characters. At the first difference (or at the end), it returns the difference of ASCII values: 'c' − 'd' = −1. Equal strings reach
'\0'together, giving 0.
Also see concatenate two strings using pointer.
How Reversing a String Works
Use two indexes: i from the start and j from the end (just before '\0'). Swap, then move them toward each other.
Take "CODE" (length 4, so j starts at 3):
i=0 j=3 : swap C,E -> E O D C
i=1 j=2 : swap O,D -> E D O C
i=2 j=1 : i >= j, stop result: "EDOC"
A palindrome reads the same forwards and backwards, like "madam", "level" or "racecar". Check it by comparing s[i] with s[j]: one mismatch means "not a palindrome".
Example 2: Reverse a String and Check Palindrome
#include <stdio.h>
int length(const char s[])
{
int n = 0;
while (s[n] != '\0')
n++;
return n;
}
void reverse(char s[])
{
int i = 0, j = length(s) - 1;
char temp;
while (i < j)
{
temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
}
int is_palindrome(const char s[])
{
int i = 0, j = length(s) - 1;
while (i < j)
{
if (s[i] != s[j])
return 0; /* one mismatch is enough */
i++;
j--;
}
return 1;
}
int main(void)
{
char word[] = "program";
char *tests[] = {"madam", "racecar", "hello"}; /* list of strings: next lesson */
int k;
reverse(word);
printf("Reversed: %s\n", word);
for (k = 0; k < 3; k++)
{
printf("%-8s: %s\n", tests[k],
is_palindrome(tests[k]) ? "palindrome" : "not palindrome");
}
return 0;
}
Output
Reversed: margorp madam : palindrome racecar : palindrome hello : not palindrome
reverseswaps in place, so it needs a modifiable array (char word[]), not a string literal.is_palindromeonly reads, so string literals like"madam"are fine.%-8sprints the word left-aligned in 8 spaces, which lines up the colons.- The loops run only n/2 times, so both are O(n).
Checking a number instead? See the palindrome number program in C.
Important Points to Remember
- Read strings by looping until '\0'.
- When building a string, always end it with '\0'.
- Concatenate by starting at the old '\0' of the destination.
- Compare by returning the ASCII difference at the first mismatch.
- Reverse and palindrome use two indexes (i from start, j from end) and loop while i < j.
- Don't modify string literals; use a char array.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
Forgetting dest[i] = '\0' | Garbage printed after the text | Add '\0' after the copy loop |
Starting j at length | Swaps '\0' to the front: empty string | j = length - 1 |
Reverse loop while (i <= n) over the whole string | Swaps twice: string unchanged | while (i < j) |
Reversing a literal: char *s = "abc"; reverse(s); | Crash (literals are read-only) | char s[] = "abc"; |
| Palindrome printed inside the loop | Many lines of output | Decide after the loop (or return early) |
String Programs Practice Questions
- Write the loop condition to find the length of a string without strlen.
- Why must a copy loop be followed by
dest[i] = '\0'? - In my_strcat, where does writing start in the destination?
- Is "Madam" (capital M) a palindrome according to Example 2? Why?
- How many swaps does reversing a 9-letter string need?
Show answers
while (s[i] != '\0') i++;- The loop stops before copying
'\0', so the new string has no end mark without it. - At index
length(dest), the position of its old'\0'. - No: 'M' and 'm' have different ASCII values. Convert both to lowercase first to ignore case.
- 4 swaps (9 / 2; the middle letter stays).
Coding Exercise
Without any library function, convert a string to uppercase. Small letters 'a'–'z' become capitals when you subtract 32 (because 'a' = 97 and 'A' = 65). Test with "hello c 2025".
Show solution
#include <stdio.h>
int main(void)
{
char s[] = "hello c 2025";
int i;
for (i = 0; s[i] != '\0'; i++)
{
if (s[i] >= 'a' && s[i] <= 'z')
s[i] = s[i] - 32; /* or s[i] - 'a' + 'A' */
}
printf("%s\n", s);
return 0;
}
HELLO C 2025
Quick Quiz: String Programs Without Library Functions (MCQ)
-
A loop to find string length stops when:
A)
s[i] == ' 'B)s[i] == '\0'C)i == 100D)s[i] == '\n' -
Which of these is a palindrome?
A) "hello" B) "noon" C) "moon" D) "level up"
-
To reverse "abcd" in place, j starts at index:
A) 4 B) 3 C) 0 D) 2
-
A hand-written strcmp returns
a[i] - b[i]. For "cat" and "car" it returns:A) 0 B) A positive value C) A negative value D) 1 always
-
To convert
'b'to'B':A) Add 32 B) Subtract 32 C) Multiply by 2 D) Subtract 48
Show answers
- B:
'\0'. - B: "noon".
- B: 3 (length − 1).
- B: positive ('t' 116 − 'r' 114 = 2).
- B: subtract 32.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Length | Count until '\0' |
|---|---|
| Copy | Copy chars, then dest[i] = '\0' |
| Concatenate | Start at dest's old '\0' |
| Compare | Return a[i] − b[i] at first mismatch |
| Reverse | Swap s[i], s[j] while i < j |
| Palindrome | s[i] == s[j] for all pairs |
| Lower → upper | − 32 |
Frequently asked questions
- How do you find the length of a string without strlen?
- Start a counter at 0 and increase it until s[i] is '\0'.
- How do you reverse a string without strrev?
- Swap the first and last characters, move inward, and stop when i >= j.
- How do you check if a string is a palindrome?
- Compare characters from both ends; if all pairs match, it is a palindrome.
Remember
- Walk till \0, end with \0.
- Reverse/palindrome = two pointers meeting in the middle.
Next Topic
Next lesson: Array of Strings in C. You will store many strings, like a list of names, in a 2D char array.