Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reversing string input not giving right output

Here’s how I’m going about it:

int maxIndex = input.length() - 1;

    for (int index = 0; index <= maxIndex; index++)
    {
        char temp = input[index];
        input[index] = input[maxIndex - index];
        input[maxIndex - index] = input[index];
    }

The input is taken in a string variable called input. Now if the size of the input array is 3, the indexes are 0, 1 and 2

According to me there shouldn’t have been any problems but testing this gives me:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Input: pli
Output: ili

Why don’t the first and last elements get swapped properly?

>Solution :

There are 2 issues here:

  1. the last assignment uses input[index] instead of temp on the right hand side
  2. You iterate until the index reaches the end, which means every corresponding pair of indices is swapped twice resulting in the original string after fixing just (1.)
if (!input.empty())
{
    for (size_t index = 0, index2 = input.size() - 1; index < index2; ++index, --index2)
    {
        char temp = input[index];
        input[index] = input[index2];
        input[index2] = temp;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading