Extract a Word from a String

161 views Asked by At

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]));
}
2

There are 2 answers

1
πάντα ῥεῖ On

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.

0
Vaibhav Bajaj On

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.