Two methods for reversing a text string in c++
Hi, this is Mazen. Today, I'm going to solve with you a programming question using C++. You don't necessarily have to use C++ to solve this example, all I care about is the concept not the programming language being used. So just understand the step and apply it in whatever language you prefer.
Our example for this blog is reversing a text and then outputting the reversed text. We use two simple approaches, the first one is using the normal class string that C++ and most of the modern programming languages provide. The other approach is using the array of characters, which typically is referred to as "c-string".
Write a program that reverses a string and prints it on the screen
Using C++ string class:
Step 1: Prompt the user to enter a text and store it in a string variable using getline() function ( make sure you include the <string> header file ).
std::cout << "Enter a text: "; std::string text; getline(std::cin, text);
Step 2: Print the reversed text as follows:
std::cout << "The reversed text: "; for (int i = text.size() - 1; i >= 0; i--) std::cout << text[i];
Putting it all together
#include <iostream>
#include <string>
int main()
{
std::cout << "Enter a text: ";
std::string text;
getline(std::cin, text);
std::cout << "\nThe reversed text: ";
for (int i = text.size() - 1; i >= 0; i--)
std::cout << text[i];
std::cout << "\n\n";
system("pause");
return 0;
}
Output:
Another approach: ( using c-string - array of characters )
Step 1: Declare an array of type char ( c-string ) with the size of 100 character.
char text[100];
std::cout << "Enter a text up to 99 character length: "; std::cin.get(text, 99);
Note: The character array can hold just 99 element not 100, because the 100th element is reserved for the null terminating character (\0).
std::cout << "The reversed text: "; for (int i = strlen(text) - 1; i >= 0; i--) std::cout << text[i];
Putting it all together:
#include <iostream>
int main()
{
char text[100];
std::cout << "Enter a text up to 99 character length: ";
std::cin.get(text, 99);
std::cout << "\nThe reversed text: ";
for (int i = strlen(text) - 1; i >= 0; i--)
std::cout << text[i];
std::cout << "\n\n";
system("pause");
return 0;
}
Output:
As you can notice, the first method is more effective and easier to manage. In addition, the second approach "c-string" has the major disadvantage that it is statically sized. In our code, we guaranteed 99 characters to be stored, but what if the user enter just 10 characters? the rest 89 elements of the array would reserve unused memory space. Moreover, the user may need to enter a text more than 99 digit long, in this case the string class approach is more appropriate. So, if the programming language you use does provide string class, I would rather using it over c-string approach.
Comments
Post a Comment