Introduction
Reversing a string is a common task in programming that involves rearranging the characters of the string so that they appear in the opposite order. This operation can be useful in various applications, such as checking for palindromes, manipulating text, or simply for aesthetic purposes. In C, strings are typically represented as arrays of characters, which allows us to manipulate them using standard array operations.
#include <stdio.h>
#include <string.h>
#define MAX 100 // Maximum size of the string
void reverseString(char str[]) {
int start = 0;
int end = strlen(str) - 1;
char temp;
while (start < end) {
// Swap characters
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
int main() {
char str[MAX];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// Remove the newline character if present
str[strcspn(str, "\n")] = '\0';
printf("Original String: %s\n", str);
reverseString(str);
printf("Reversed String: %s\n", str);
return 0;
}
Explanation
- Includes and Defines: The program includes the
stdio.handstring.hheaders for input/output and string manipulation functions, respectively. It defines a constantMAXfor the maximum size of the string. - Reverse Function: The
reverseStringfunction takes a string as input and reverses it in place:- It initializes two pointers,
startandend, to the beginning and end of the string. - A
whileloop runs as long asstartis less thanend. Inside the loop, it swaps the characters at these positions and moves the pointers towards the center.
- It initializes two pointers,
- Main Function: In
main, the program:- Declares a string variable.
- Prompts the user to enter a string using
fgets, which safely reads a line of input. - Removes the newline character that
fgetsmight add usingstrcspn. - Displays the original string.
- Calls the
reverseStringfunction to reverse the string. - Finally, it prints the reversed string.
Input
The user is prompted to enter a string. Example input:
Enter a string: Hello, World!
Output
The program outputs both the original and reversed strings. For the example input, the output will be:
Original String: Hello, World!
Reversed String: !dlroW ,olleH
Conclusion
This C program effectively demonstrates how to reverse a string using basic string manipulation techniques. Understanding how to work with strings and arrays is crucial in C programming, as it forms the basis for many text processing tasks. The code can be easily adapted to handle different input sizes or to implement other string-related functionalities, making it a versatile example for learning about strings in C.