Different methods to reverse a string in C/C++

2.2

Here, we are discussing some of the methods to reverse strings in C++:

  1. Write own reverse function by swapping characters: One simple solution is two write our own reverse function to reverse a string in C++.
    // A Simple C++ program to reverse a string
    #include<bits/stdc++.h>
    using namespace std;
    
    // Function to reverse a string
    void reverseStr(string &str)
    {
        int n = str.length();
    
        // Swap character starting from two
        // corners
        for (int i=0; i<n/2; i++)
           swap(str[i], str[n-i-1]);
    }
    
    // Driver program
    int main()
    {
       string str = "geeksforgeeks";
       reverseStr(str);
       cout << str;
       return 0;
    }
    

    Output :

    skeegrofskeeg
  2. Using inbuilt “reverse” function: There is a direct function in “algorithm” header file for doing reverse that saves our time when programming.
    // Reverses elements in [begin, end]
    void reverse (BidirectionalIterator begin, 
    BidirectionalIterator end);
    
    // A quickly written program for reversing a string
    // using reverse()
    #include<bits/stdc++.h>
    using namespace std;
    int main()
    {
       string str = "geeksforgeeks";
       
       // Reverse str[beign..end]
       reverse(str.begin(),str.end());
       
       cout << str;
       return 0;
    }
    

    Output :

    skeegrofskeeg
  3. Write own reverse function with strlen(): strlen is an inbuilt library function used to calculate string length. need to be included to use this method.
    // CPP program to reverse a 
    // given string using
    // strlen()
    #include<stdio.h>
    #include<string.h>
     
    // Function to reverse a string
    void * reverse(char * str )
    { 
        int i, len ;
         
        // calculating length of the string
        len = strlen(str);
         
        for( i=len ; i>=0 ; i--)
        // *(str+i) is the character at the ith index 
        // of the string
            printf( "%c", *(str+i));
    }
     
    // Driver code
    int main( void )
    {
        char a[] = "Geeks for Geeks" ;
         
        reverse(a);
        return(0);
    }
    

    Output:

    skeeg rof skeeG
    
  4. Reverse a constant string: If the string is a const string (not editable), then how do we create a string which is the reverse of given string?
    We need to create an array and return the pointer of that. Let’s see how to do it:

    // C Program to reverse a constant string 
    // and return the pointer of that
    
    #include <stdio.h>
    #include <string.h>
    #include <malloc.h>
    
    // Function to reverse string and return reverse string pointer of that
    char* ReverseConstString(char *str)
    {
    	int start, end, len;
    	char temp, *ptr = NULL;
    	
    	// find length of string
    	len = strlen(str);	
    	
    	// create dynamic pointer char array
    	ptr = malloc(sizeof(char)*(len+1)); 
    	
    	// copy of string to ptr array
    	ptr = strcpy(ptr,str);			 
    	
    	// swapping of the characters
    	for (start=0,end=len-1; start<=end; start++,end--)
    	{
    		temp = ptr[start];
    		ptr[start] = ptr[end];		 
    		ptr[end] = temp;
    	}
    	
    	// return pointer of reversed string
    	return ptr; 
    }
    
    // Driver Code
    int main(void) 
    {
        const char const *str = "GeeksforGeeks";
    	printf("%s", ReverseConstString(str));
    	return 0;
    }
    

    Output:

     skeeGrofskeeG
    

This article is contributed by Priyam kakati, Ranju Kumari, Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:



2.2 Average Difficulty : 2.2/5.0
Based on 31 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.