Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

String reversal

/*
	C++ program for String reversal by lolman_ks.
    This logic can be used to build this program in other languages also.
*/
/*
	Logic: Place one counter at the start and one at the end.
    Keep swapping the characters while the 2nd counter > 1st Counter.
*/

#include <iostream>
using namespace std;

string returnReversedString(string text){
    int counter_1 = 0; //Place one counter at the start.
  	int counter_2 = text.length() - 1; //And the other at the end.

  	//Run a loop till the 1st counter is less than the 2nd.
    while(counter_1 < counter_2){
        char save = (char)(text[counter_1]); //Save the value of text[counter_1].

        text[counter_1] = text[counter_2];
        text[counter_2] = save;
      	//The above two lines swap the characters.

        ++counter_1;
        --counter_2;
    }
	return text;
}

//Implementations of this function.

int main(){
	cout << returnReversedString("hello") << endl; //Returns "olleh".
  	return 0;
}

/*
	I hope if you find my answers are useful. Please promote them if they are.
    #lolman_ks.
*/
 
PREVIOUS NEXT
Tagged: #String #reversal
ADD COMMENT
Topic
Name
3+7 =