Cover Image for Reverse a String in C
83 views

Reverse a String in C

To reverse a string in C, you can write a simple program that swaps characters from the beginning and end of the string until you reach the middle of the string. Here’s an example of how to reverse a string in C:

C
#include <stdio.h>
#include <string.h>

// Function to reverse a string
void reverseString(char *str) {
    int length = strlen(str);
    int start = 0;
    int end = length - 1;

    while (start < end) {
        // Swap characters at start and end positions
        char temp = str[start];
        str[start] = str[end];
        str[end] = temp;

        // Move the start and end pointers inward
        start++;
        end--;
    }
}

int main() {
    char str[] = "Hello, World!";

    printf("Original string: %s\n", str);

    // Reverse the string
    reverseString(str);

    printf("Reversed string: %s\n", str);

    return 0;
}

In this program:

  1. We include the <stdio.h> and <string.h> headers for input/output and string manipulation functions.
  2. We define a function reverseString that takes a character array (char*) as its argument.
  3. Inside the reverseString function, we use a while loop to swap characters from the beginning and end of the string until the start pointer is less than the end pointer.
  4. The strlen() function is used to find the length of the input string.
  5. We use a temporary variable temp to perform the character swap.
  6. In the main function, we declare an input string str, print it, call the reverseString function to reverse it, and then print the reversed string.

When you run this program, it will output:

Plaintext
Original string: Hello, World!
Reversed string: !dlroW ,olleH

The reverseString function modifies the input string in place, reversing it without requiring additional memory for a new string.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS