Program to Reverse a String using Pointers
Given a string, the task is to reverse this String using pointers. Examples:
Input: Beginner Output: skeeG Input: w3wiki 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; // Function to reverse the string // using pointers void reverseString( char * str) { int l, i; char *begin_ptr, *end_ptr, ch; // Get the length of the string l = strlen (str); // Set the begin_ptr // initially to start of string begin_ptr = str; //Setting end_ptr initially to //the end of the string end_ptr = str + l - 1; // Swap the char from start and end // index using begin_ptr and end_ptr for (i = 0; i < (l - 1) / 2; i++) { // swap character ch = *end_ptr; *end_ptr = *begin_ptr; *begin_ptr = ch; // update pointers positions begin_ptr++; end_ptr--; } } // Driver code int main() { // Get the string char str[100] = "w3wiki" ; cout<< "Enter a string: " <<str<<endl; // Reverse the string reverseString(str); // Print the result printf ( "Reverse of the string: %s\n" , str); return 0; } // This code is contributed by akashish__ |
C
#include <stdio.h> #include <string.h> // Function to reverse the string // using pointers void reverseString( char * str) { int l, i; char *begin_ptr, *end_ptr, ch; // Get the length of the string l = strlen (str); // Setting the begin_ptr // to start of string begin_ptr = str; //Setting the end_ptr the end of //the string end_ptr = str + l - 1; // Swap the char from start and end // index using begin_ptr and end_ptr for (i = 0; i < (l - 1) / 2; i++) { // swap character ch = *end_ptr; *end_ptr = *begin_ptr; *begin_ptr = ch; // update pointers positions begin_ptr++; end_ptr--; } } // Driver code int main() { // Get the string char str[100] = "w3wiki" ; printf ( "Enter a string: %s\n" , str); // Reverse the string reverseString(str); // Print the result printf ( "Reverse of the string: %s\n" , str); return 0; } |
Output:
Enter a string: w3wiki 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.
Contact Us