1

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.

Mat
  • 202,337
  • 40
  • 393
  • 406
mharris7190
  • 1,334
  • 3
  • 20
  • 36
  • http://stackoverflow.com/questions/236129/splitting-a-string-in-c - you'll get lots of ideas from there. – Mat Aug 26 '12 at 16:56

1 Answers1

4

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();
}
jrok
  • 54,456
  • 9
  • 109
  • 141
  • is the & for pass by reference? im new to c++ and have been confused by the (const and the &) in the parameters. & is pass by ref, right? but the const is so that it can't be changed? – mharris7190 Aug 26 '12 at 18:32
  • Correct. You avoid potentialy expensive copies this way. Stringstream will make a copy of the string in it's own buffer, anyway. – jrok Aug 26 '12 at 18:37