Two methods for reversing a text string in c++

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".

The question says:

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:

- Create a for loop that passes through the string indexes but in the reversed manner. We start printing the value of the last index first, and the first index's value is printed last. To clarify that, if the entered text is "mazen", the last letter 'n' is printed first. Next, the letter 'e' gets printed until that the loop reaches the last element of the string array, which in this example is 'm'.

    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:

reversing a text string in c++


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];

Note: Increasing the size of the array provides more text length but with the cost of reserving more space of the memory.

Step 2: Prompt the user to enter a text up to 99 character length. Use the method get() instead of using the cin statement, in order to get spaces the user might enter.

    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).


Step 3: Output the reversed text using the following logic:

- We start outputting the text from the last entered character, and end up with first one.
- We're getting advantage of the method strlen() ( string length ), in order to reach the last character in the text. The index of the last character is the string length minus one, because the last index is specialized for the terminating character (\0).
- We create a loop that passes through the c-string array. the initial value is the last index of the last character which is ( strlen(text) - 1 ). The condition is that the loop should stop at the index 0 of the array. Then the initial value is incremented at every cycle.
- Inside of the body of the loop, we just write the output statement to print the current value of the text array.

    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:

reversing a text string in c++


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

Popular posts from this blog

Finding (positive - negative - odd - even - zero) numbers in an array

Taking inputs from the user, storing them in a (1D-2D-3D) array and printing them on the screen in c++