Program to Reverse a String using Pointers
Last Updated :
11 Dec, 2022
Given a string, the task is to reverse this String using pointers. Examples:
Input: Geeks
Output: skeeG
Input: GeeksForGeeks
Output: skeeGroFskeeG
Approach: This method involves taking two pointers, one that points at the start of the string and the other at the end of the string. The characters are then reversed one by one with the help of these two pointers. Program:
C++
#include <bits/stdc++.h>
using namespace std;
void reverseString( char * str)
{
int l, i;
char *begin_ptr, *end_ptr, ch;
l = strlen (str);
begin_ptr = str;
end_ptr = str + l - 1;
for (i = 0; i < (l - 1) / 2; i++) {
ch = *end_ptr;
*end_ptr = *begin_ptr;
*begin_ptr = ch;
begin_ptr++;
end_ptr--;
}
}
int main()
{
char str[100] = "GeeksForGeeks" ;
cout<< "Enter a string: " <<str<<endl;
reverseString(str);
printf ( "Reverse of the string: %s\n" , str);
return 0;
}
|
C
#include <stdio.h>
#include <string.h>
void reverseString( char * str)
{
int l, i;
char *begin_ptr, *end_ptr, ch;
l = strlen (str);
begin_ptr = str;
end_ptr = str + l - 1;
for (i = 0; i < (l - 1) / 2; i++) {
ch = *end_ptr;
*end_ptr = *begin_ptr;
*begin_ptr = ch;
begin_ptr++;
end_ptr--;
}
}
int main()
{
char str[100] = "GeeksForGeeks" ;
printf ( "Enter a string: %s\n" , str);
reverseString(str);
printf ( "Reverse of the string: %s\n" , str);
return 0;
}
|
Output:
Enter a string: GeeksForGeeks
Reverse of the string: skeeGroFskeeG
Time Complexity: O(N), where N represents the length of the given string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Share your thoughts in the comments
Please Login to comment...