0

I'm working on a homework assignment, and I can't seem to get this function right. Does anyone have any ideas on why this won't work to create a substring consisting of the characters in between two spaces (word 0, word 1, etc...)?

string extractWord(string s, int wordNum)
{
    int wordIndices[10];
    int i = 0;
    for (int z = 0; z < s.length(); z++)
    {
        if (isspace(s.at(z))==true)
        {
            wordIndices[i] = z;
            i++;
        }
    }
    return s.substr(wordIndices[wordNum], abs(wordIndices[wordNum+1] - wordIndices[wordNum]));
}
  • If `s` is `"word1 word2"`, then, `wordIndices[0]` will be `5`. I don't think you want that. In other words, if there are no leading whitespace characters, `wordIndices[0]` must be set to `0`. – R Sahu Jul 02 '16 at 05:16
  • BTW, you can treat `std::string` as an array and don't need the `at` function, such as `s[z]`. – Thomas Matthews Jul 02 '16 at 05:48

2 Answers2

0

The easiest way is to use a std::istringstream:

std::string extractWord(std::string s, int wordNum)
{
     std::istringstream iss(s);
     std::string word;
     std::vector<std::string> words;
     while(iss >> word) {
         words.push_back(word);
     }
     return words[wordnum];
}

Be aware of exceptions thrown, when wordnum goes out of bounds.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • I already know, you'll come up here saying _"my assignment restricts me to use blah, blah"_, though such doesn't matter in real world programming with c++. – πάντα ῥεῖ Jul 02 '16 at 05:26
0

In this case, before the for loop, you should try adding this if statement:

if (! isspace(s.at(0))
{
  wordIndices[i] = 0;
  i++;
}

The issue you are facing is if wordNum is 1 and there are no leading spaces then wordIndices[0] is set to the first space which does not work well with your code.
Also, after the for loop, you should put:

wordIndices[i] = s.length()

as when extracting the last word, wordIndices[wordNum+1] has a junk value.

Vaibhav Bajaj
  • 1,934
  • 16
  • 29