mharris7190
mharris7190

Reputation: 1374

Pig Latin string iteration, multiple word

I'm reading a book for C++ and one of the exercises to create a pig latin translator. I have figured out all the necessary steps to translate a single word. Now I am having a lot of trouble with making a function for handling multi-word strings.

Basically I need help with the sort of standard idiom for iterating through each word of a string and performing an action on each word.

The function I have so far is sloppy at best and I am just stuck.

string sentenceToPigLatin(string str) {
    string result = "";
    for (int i = 0; i < str.length(); i++) {
        char ch = str.at(i);
        if (ch == ' ') {
            result += toPigLatin(str.substr(0, i));
            str = str.substr(i);
        }
    }
    return result;
}

You can assume toPigLatin() performs the correct procedure for a word not containing whitespace.

Upvotes: 1

Views: 915

Answers (1)

jrok
jrok

Reputation: 55395

You can put the whole string in a stringstream and use extraction operator to get out a single word:

#include <sstream>  // for stringstreams

string sentenceToPigLatin(const string& str)
{ 
    istringstream stream(str);
    ostringstream result;
    string temp;
    while (stream >> temp)
            result << toPigLatin(temp) << ' ';
    return result.str();
}

Another way is to use standard algorithms together with stream iterators:

#include <algorithm> // for transform
#include <iterator>  // for istream_iterator and ostream_iterator

string sentenceToPigLatin(const string& str)
{ 
    istringstream stream(str);
    ostringstream result;
    transform(istream_iterator<string>(stream),
              istream_iterator<string>(),
              ostream_iterator<string>(result, " "),
              toPigLatin);
    return result.str();
}

Upvotes: 4

Related Questions