HELP ME REVERSE PLEASE?

The following code translates english to pig latin. I need it to do the opposite, basically I need the user to enter a pig latin word such as "igpay" then remove the last 2 letters "ay". After that the output will look like "igp" in which I then need the last character in the string to be moved to the start of the string so it will display "pig". Can anyone help me with this, please?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <string>
using namespace std;

// takes a string argument and returns the pigLatin equivalent
string pigLatin(string);

int main()
{
    string mySentence; 

    getline(cin, mySentence);
    mySentence = pigLatin(mySentence);
    cout << mySentence << endl;

    return 0;
}

string pigLatin(string word){

    //pigLatWord holds word translated in pig latin.
    //pigLatSentence holds entire translated sentence.
    string pigLatWord, pigLatSentence = "";
    int length = 0, index = 0;

    while (word[index] != '\0'){
        // .find returns -1 if no match is found
        if (word.find(' ', index) != -1){
            length = word.find(' ', index);
            length -= index;//length - index = the number of characters in a word
            pigLatWord = word.substr(index, length);
            pigLatWord.insert(length, " ");
            pigLatWord.insert(length, 1, word[index]);//first letter is inserted at the end of the string
            pigLatWord.erase(0, 1);// erase first letter in string
            index += length + 1;//adding one moves index from 'space' to first letter in the next word
        }
        else{
            pigLatWord = word.substr(index);
            length = pigLatWord.length();
            pigLatWord.insert(length, " ");
            pigLatWord.insert(length, 1, word[index]);
            pigLatWord.erase(0, 1);
            index = word.length();
        }

        pigLatSentence += (pigLatWord + " ");
    }
    return pigLatSentence;
}
Last edited on
To erase the last letters you can use erase():

pigLatWord.erase(pigLatWord.size() - 2, 2);

or pop_back():
1
2
pigLatWord.pop_back();
pigLatWord.pop_back();


To move the last letter:
1
2
pigLatWord.insert(0, 1, pigLatWord.back());
pigLatWord.pop_back();
Topic archived. No new replies allowed.