In this article, we will discuss a detailed approach to writing a C program that can reverse a string. This is a fundamental operation in string manipulation and is an important concept in computer science and programming.
A string in C programming is an array of characters ending with a null character (`\0`). For example, the string “hello” can be represented as ‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’ in C.
Approach to Reverse a String
There are multiple ways to reverse a string in C. Here, we will discuss two common methods:
- Using a temporary array
- Using two pointers
Method 1: Using a Temporary Array
This method involves creating a new temporary array and storing the elements of the original string in reverse order. The following are the steps involved in this approach:
- Find the length of the original string.
- Create a new array of the same length.
- Copy the characters from the original string to the new array, but in reverse order.
- Append a null character (\0) to the end of the new array.
- Print the new array.
Here is the C code for this approach:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <stdio.h> #include <string.h> int main() { char str[100], rev[100]; int len, i, index = 0; printf("Enter a string: "); gets(str); // read the input string len = strlen(str); // calculate the length of the string // reverse the string for(i = len - 1; i >= 0; i--) { rev[index] = str[i]; index++; } rev[index] = '\0'; // append null character to the end printf("Reversed string: %s", rev); return 0; } |
Method 2: Using Two Pointers
This approach involves using two pointers to swap characters in the original string, which ultimately results in a reversed string. The steps in this approach are:
- Declare two pointers, start and end.
- Point start to the beginning of the string and end to the end of the string (excluding the null character).
- Swap the characters pointed by start and end.
- Move start one position to the right and end one position to the left.
- Repeat steps 3-4 until start and end cross each other.
Here is the C code for this approach:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #include <stdio.h> #include <string.h> void reverseString(char* str) { int len, start, end; char temp; len = strlen(str); start = 0; end = len - 1; while(start < end) { // swap characters temp = str[start]; str[start] = str[end]; str[end] = temp; // move pointers start++; end--; } } int main() { char str[100]; printf("Enter a string: "); gets(str); // read the input string reverseString(str); printf("Reversed string: %s", str); return 0; } |
Conclusion
Reversing a string in C programming is a common task that helps to improve your understanding of string manipulation, arrays, and pointers. The two methods discussed here are quite efficient, but the second method is more memory-efficient as it does not require a new array to store the reversed string.