Reverse A String In C Without Using Inbuilt Function
In this article, you will learn various methods to reverse a string in C without relying on standard library functions designed specifically for string reversal. We will explore practical, step-by-step solutions suitable for different scenarios.
Problem Statement
Reversing a string involves rearranging its characters such that the last character becomes the first, the second-to-last becomes the second, and so on, until the first character becomes the last. The core challenge is to achieve this transformation using fundamental C programming constructs like loops, arrays, and pointers, without leveraging higher-level string manipulation functions from the standard library (such as strrev). This task is a common interview question and a good exercise for understanding memory manipulation in C.
Example
Consider the input string "hello". The desired output after reversal should be "olleh".
Background & Knowledge Prerequisites
To effectively understand the solutions presented, readers should have a basic grasp of:
- C Language Fundamentals: Variables, data types, control flow (loops like
forandwhile). - Arrays: How character arrays (strings) are declared and manipulated in C.
- Pointers: Basic understanding of pointer arithmetic and dereferencing.
- Memory Management: A general idea of how data is stored in memory.
For setup, you will only need a C compiler (like GCC) and a text editor.
Use Cases or Case Studies
Reversing a string might seem like a simple academic exercise, but it has several practical applications:
- Palindrome Detection: To check if a string reads the same forwards and backward (e.g., "madam"), reversing the string is a common first step.
- Data Processing: In some data transformation tasks, reversing specific parts of a string might be required before further analysis.
- Encryption Algorithms: Certain simple cryptographic techniques might involve reversing parts of a message or key as part of their encoding or decoding process.
- Text Formatting and Display: For specialized text effects or when displaying text in certain right-to-left contexts, string reversal might be a utility function.
- Algorithm Challenges: It's a foundational problem that helps build intuition for more complex string algorithms and memory manipulation.
Solution Approaches
We will explore two effective methods to reverse a string in C without using inbuilt string reversal functions. First, we'll implement a custom function to determine the length of the string, as strlen is a standard library function.
Custom String Length Function
Before we reverse a string, we often need its length. We can implement a simple function to calculate it manually.
- Summary: Iterates through the string until the null terminator
\0is found, counting characters along the way. - Code Example:
// Custom String Length Calculation
#include <stdio.h> // Required for printf
// Function to calculate string length manually
int get_string_length(char* str) {
int length = 0;
while (str[length] != '\\0') {
length++;
}
return length;
}
int main() {
char myString[] = "ReverseMe";
int len = get_string_length(myString);
printf("Original String: %s\\n", myString);
printf("Length of string: %d\\n", len);
return 0;
}- Sample Output:
Original String: ReverseMe
Length of string: 9- Stepwise Explanation:
- The
get_string_lengthfunction takes a character pointerstras input. - An integer
lengthis initialized to 0. - A
whileloop continues as long as the character at the currentlengthindex is not the null terminator\0. - In each iteration,
lengthis incremented. - Once the null terminator is reached, the loop terminates, and the final value of
length(which represents the count of characters before\0) is returned.
Approach 1: In-Place Reversal Using Two Pointers
This is one of the most efficient and common methods, as it modifies the string directly without needing extra memory proportional to the string's length.
- Summary: Uses two pointers, one starting at the beginning and the other at the end of the string, swapping characters until they meet in the middle.
- Code Example:
// In-Place String Reversal (Two Pointers)
#include <stdio.h> // Required for printf
// Custom string length function
int get_string_length(char* str) {
int length = 0;
while (str[length] != '\\0') {
length++;
}
return length;
}
// Function to reverse a string in-place
void reverse_string_inplace(char* str) {
int length = get_string_length(str);
int start = 0;
int end = length - 1;
char temp; // Temporary variable for swapping
while (start < end) {
// Swap characters at start and end positions
temp = str[start];
str[start] = str[end];
str[end] = temp;
// Move pointers inward
start++;
end--;
}
}
int main() {
char myString[] = "programming"; // Modifiable string
char anotherString[] = "hello world";
printf("Original string 1: %s\\n", myString);
reverse_string_inplace(myString);
printf("Reversed string 1: %s\\n", myString);
printf("\\nOriginal string 2: %s\\n", anotherString);
reverse_string_inplace(anotherString);
printf("Reversed string 2: %s\\n", anotherString);
return 0;
}- Sample Output:
Original string 1: programming
Reversed string 1: gnimmargorp
Original string 2: hello world
Reversed string 2: dlrow olleh- Stepwise Explanation:
- First, the
get_string_lengthfunction (defined previously) is called to determine the string's length. - Two integer pointers,
startandend, are initialized.startpoints to the first character (index 0), andendpoints to the last character (indexlength - 1). - A
whileloop continues as long asstartis less thanend. This ensures that characters are swapped only once and the middle character (for odd-length strings) remains in place. - Inside the loop:
- The character at
str[start]is stored in a temporary variabletemp.
- The character at
str[end] is assigned to str[start].temp (original str[start]) is assigned to str[end].start is incremented, moving towards the right.end is decremented, moving towards the left.- When
startbecomes greater than or equal toend, the loop terminates, and the string is fully reversed.
Approach 2: Reversal Using an Auxiliary Array
This method involves creating a temporary array to store the reversed string, then copying it back to the original or using the temporary array as the result.
- Summary: Copies characters from the original string into a new auxiliary array in reverse order, then potentially copies back.
- Code Example:
// String Reversal (Auxiliary Array)
#include <stdio.h> // Required for printf
// Custom string length function
int get_string_length(char* str) {
int length = 0;
while (str[length] != '\\0') {
length++;
}
return length;
}
// Function to reverse a string using an auxiliary array
void reverse_string_auxiliary(char* original_str, char* reversed_str) {
int length = get_string_length(original_str);
int i, j;
// Copy characters from original_str to reversed_str in reverse order
for (i = 0, j = length - 1; i < length; i++, j--) {
reversed_str[i] = original_str[j];
}
reversed_str[length] = '\\0'; // Null-terminate the reversed string
}
int main() {
char myString[] = "computers";
char reversed[50]; // Auxiliary array to store the reversed string
printf("Original string: %s\\n", myString);
reverse_string_auxiliary(myString, reversed);
printf("Reversed string: %s\\n", reversed);
char anotherString[] = "data structures";
char reversed2[50];
printf("\\nOriginal string: %s\\n", anotherString);
reverse_string_auxiliary(anotherString, reversed2);
printf("Reversed string: %s\\n", reversed2);
return 0;
}- Sample Output:
Original string: computers
Reversed string: sretupmoc
Original string: data structures
Reversed string: serutcurts atad- Stepwise Explanation:
- The
get_string_lengthfunction is used to determine the length oforiginal_str. - A
forloop is initialized with two counters:istarting from 0 (for thereversed_strindex) andjstarting fromlength - 1(for theoriginal_strindex). - The loop continues as long as
iis less thanlength. - In each iteration, the character from
original_strat indexjis copied toreversed_strat indexi. iis incremented to move forward in thereversed_str, andjis decremented to move backward in theoriginal_str.- After the loop completes, a null terminator
\0is added to the end ofreversed_strto ensure it is a valid C string. - It's crucial that
reversed_strhas enough allocated memory to hold the reversed string, including the null terminator.
Conclusion
Reversing a string without built-in functions is a fundamental task that reinforces understanding of C's memory and pointer manipulation. The two-pointer in-place method is generally preferred for its efficiency in terms of memory usage, as it requires only a temporary variable for swapping. The auxiliary array method is simpler to conceptualize but uses additional memory proportional to the string's length. Both approaches are valuable for developing robust C programming skills.
Summary
- Problem: Reverse a string in C without using standard library functions like
strrev. - Custom Length: A custom
get_string_lengthfunction is essential to avoid usingstrlen. - In-Place Reversal (Two Pointers):
- Uses two pointers,
startandend, moving inwards from opposite ends of the string. - Swaps characters at
startandenduntilstartcrosses or meetsend. - Memory efficient as it modifies the original string directly.
- Auxiliary Array Reversal:
- Creates a temporary array of sufficient size.
- Copies characters from the original string in reverse order into the temporary array.
- Requires additional memory proportional to the string's length.
- Null Termination: Always remember to null-terminate strings, especially when creating new ones or modifying them manually.