Reverse the String Using Pointer in C

We will use here two pointers, one is start pointer and another is end pointer. and by swapping the character we will proceed to achieve, reverse the characters similar to what we have done in the first method.

Implementation

C




// C program to reverse a string using pointers
#include <stdio.h>
#include <string.h>
 
// function to reverse the string
void stringReverse(char* str)
{
    int len = strlen(str);
    // pointers to start and end
    char* start = str;
    char* end = str + len - 1;
 
    while (start < end) {
        char temp = *start;
        *start = *end;
        *end = temp;
        start++;
        end--;
    }
}
 
// driver code
int main()
{
    char str[] = "string";
    printf("Original String: %s\n", str);
 
    // calling function
    stringReverse(str);
 
    printf("Reversed String: %s", str);
    return 0;
}


Output

Original String: string
Reversed String: gnirts

Reverse String in C

Reversing a string in C is a fundamental operation that involves rearranging the characters in a string so that the last character becomes the first, the second-to-last character becomes the second, and so on.

For example,

Original String:
"string"

Reversed String:
"gnirts"

In this article, we will discuss different ways to reverse a string in C with code examples.

Similar Reads

Different Ways to Reverse a String in C

There are various ways to reverse the string in the C. Some of them are discussed below:...

1. Reverse the String Using Loop

In this method,...

2. Reverse the String Using Recursion

...

3. Reverse the String Using Pointer in C

For this method, we will use recursion to swap the characters....

4. Reverse the String Using Library Function

...