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:
Input: pli
Output: ili
Why don’t the first and last elements get swapped properly?
>Solution :
There are 2 issues here:
- the last assignment uses
input[index]instead oftempon the right hand side - 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;
}
}