string.find() problem

Hello! I am attempting to write a program that translates a sentence from a file to Pig Latin. Here is the first sentence that is being translated:
I SLEPT MOST OF THE NIGHT


When the function runs through the loop the first time, it works as expected. When the loop runs a second time, length is being set to 7, instead of 5 as expected. From my understanding, .find should return a 5 since it is searching for the second space in the string from the first space in the string. Instead, it is returning a 7, which sets word to SLEPT M and it all just goes downhill from there.

Any help with this issue would be greatly appreciated! Thank you!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
std::string toPigLatin(string& data)
{
    std::string word, firstLetter, sentence = "", space = " ";
    int index = 0, length = 0;

    while(data[index] != '\0')
    {
        length = data.find(space, index);
        word = data.substr(index, length);
        firstLetter = word[index];
        word += firstLetter;
        word.erase(index, 1);
        word += "AY";
        sentence += word + " ";

        index = length + 1;

    }

    return sentence;
}
Last edited on
find should return a 5 since it is searching for the second space in the string from the first space in the string.

No. find returns: The position of the first character of the first match.

Line 8: find doesn't return the length of what it found. It returns the position of where the match occurred. First iteration, returns position (of space) = 1, which is correct for the length of the first word. Second iteration, find is called with a starting position of 2. However, find returns the POSITION (from the start of the string) of the next space. That is position 7.
Last edited on
Okay. I understand now. Thank you!
Topic archived. No new replies allowed.