YouTip LogoYouTip

C Exercise Example35

# C Programming Exercise - Example 35: String Reversal In C programming, manipulating strings is a fundamental skill. This tutorial demonstrates how to reverse a string in-place using pointers and index swapping. --- ## Problem Description Write a C program that reverses a given string in-place. For example, the string `"www.runoob.com"` should be reversed to `"moc.boonur.www"`. --- ## Algorithm Analysis To reverse a string in-place without using extra memory (except for a few temporary variables), we can use a **two-pointer** or **symmetric swapping** approach: 1. **Calculate the Length**: First, determine the length of the string ($N$) by traversing it until the null terminator (`\0`) is reached. 2. **Symmetric Swapping**: * Loop through the first half of the string (from index `0` up to `N/2 - 1`). * Swap the character at the current index `i` with its symmetric counterpart at the end of the string, which is located at index `N - 1 - i`. * Use a temporary `char` variable to facilitate the swap. This approach runs in $\mathcal{O}(N)$ time complexity and uses $\mathcal{O}(1)$ auxiliary space, making it highly efficient. --- ## Code Implementation Below is the complete C program implementing the string reversal logic: ```c #include /** * Reverses a null-terminated string in-place. * @param s Pointer to the character array (string) to be reversed. */ void reverse(char* s) { // Step 1: Calculate the length of the string int len = 0; char* p = s; while (*p != '\0') { len++; p++; } // Step 2: Swap characters symmetrically from both ends int i = 0; char temp; while (i <= len / 2 - 1) { // Swap s and s using pointer arithmetic temp = *(s + i); *(s + i) = *(s + len - 1 - i); *(s + len - 1 - i) = temp; i++; } } int main() { // Define a mutable character array char s[] = "www.runoob.com"; printf("Original string:\n'%s'\n\n", s); // Perform in-place reversal reverse(s); printf("Reversed string:\n'%s'\n", s); return 0; } ``` ### Output When you compile and run the program, it produces the following output: ```text Original string: 'www.runoob.com' Reversed string: 'moc.boonur.www' ``` --- ## Key Considerations & Best Practices ### 1. Mutable vs. Immutable Strings In C, string literals defined with double quotes (e.g., `char* s = "hello";`) are stored in a read-only data segment. Attempting to modify them will result in a **Segmentation Fault**. Always initialize the string as a character array (e.g., `char s[] = "hello";`) if you plan to modify or reverse it in-place. * **Incorrect (Undefined Behavior):** ```c char* s = "www.runoob.com"; reverse(s); // Will crash at runtime ``` * **Correct (Safe):** ```c char s[] = "www.runoob.com"; reverse(s); // Works perfectly ``` ### 2. Standard Library Alternative If you are working on production code and are allowed to use standard library functions, you can simplify the length calculation step by using `strlen()` from ``: ```c #include void reverse_standard(char* s) { int len = strlen(s); for (int i = 0; i < len / 2; i++) { char temp = s; s = s; s = temp; } } ```
← C Exercise Example36C Exercise Example34 β†’