Search code examples
c++arraysstringindexingreplace

Why does half of my indexing of a string array in a for loop works but the last half doesn't?


I am solving a problem that consists on taking a line of text and turn it backwards. For example, i have my input Welcome and output emocleW.

The problem is that my code partially works, half of the line is turned backwards but then the other half is not, it stays as if i didn´t touch it. The output looks like emocome with the input Welcome

It may be a dumb question but im new and i don´t know what to do anymore.

Also sorry if my english is kinda strange, i'm not a native speaker.

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <typeinfo>
#include <map>
#include <algorithm>

using namespace std;

int main(){
    string line; 
    cin >> line;
    int c=0;
    for (auto &&i : line)
    {
        c++; // Here i take the lenght of the line and save it in c
    }
    for (int chara = 0; chara < c; chara++) // I use this for iterating all the chars in my string
    {
        line[chara] = line[c-chara-1]; // Here i try to swap the chars by putting the value of     // the greatest index in the place 0  and so on. 
    }
    cout << line;
    return 0;
    }

I have tried doing this as well

for (int chara = 0; chara < c; chara++) 
    {
        l = c-chara-1;
        line[chara] = line[l]
    }

or

for (int chara = 0; chara < c; chara++) 
    {
        l = line[c-chara-1];
    }

but nothing works. Help :c


Solution

  • Your problem isn't a code problem so much as an algorithm problem.

    Let's look at what your code does to "Welcome":

    0 1 2 3 4 5 6
    Initial state W e l c o m e
    First loop e e l c o m e
    Second loop e m l c o m e
    Third loop e m o c o m e
    Fourth loop e m o c o m e
    Fifth loop e m o c o m e
    Sixth loop e m o c o m e
    Seventh loop e m o c o m e

    This occurs because you're copying from the end of the array to the beginning, but never saving what was at the beginning of the array to transfer it to the end. Once you got past the middle of the string you were just copying data originally from the end of the string back into the end of the string.

    To swap, you could use std::swap or code it yourself with something like:

    char temp = line[chara];
    line[chara] = line[l];
    line[l] = temp;
    

    So now let's loop over your string:

    0 1 2 3 4 5 6
    Initial state W e l c o m e
    First loop e e l c o m W
    Second loop e m l c o e W
    Third loop e m o c l e W
    Fourth loop e m o c l e W
    Fifth loop e m l c o e W
    Sixth loop e e l c o m W
    Seventh loop W e l c o m e

    Oops. We swapped the string to a reversed state, but then we swapped it right back again. The secret is to only iterate halfway through swapping characters. By the third loop iteration, we had the desired result. Conveniently, with integer math, 7 / 2 equals 3.