2016-07-02 34 views
0

我正在做一个家庭作业,而且我似乎无法获得正确的功能。有没有人有任何想法,为什么这将无法创建一个由两个空格之间的字符组成的子字符串(字0,字1等)?从字符串中提取一个字

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

如果's'是'“word1 word2”',那么'wordIndices [0]'将会是'5'。我不认为你想要那样。换句话说,如果没有前导空白字符,'wordIndices [0]'必须设置为'0'。 –

+0

顺便说一句,你可以把'std :: string'当作一个数组来处理,而不需要'at'函数,比如's [z]'。 –

回答

0

最简单的方法是使用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]; 
} 

注意异常的抛出,当wordnum去出界。

+0

我已经知道了,你会在这里说“我的任务限制了我使用等等等等”,尽管这在使用C++编程的现实世界中并不重要。 –

0

在这种情况下,之前的for循环,你应该尝试的if语句添加此:

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

你所面临的问题是,如果wordNum为1,并且没有前导空格然后wordIndices [0]设置为第一个空间不适合你的代码。
而且,在使for循环,你应该把:提取的最后一个字时

wordIndices[i] = s.length() 

如,wordIndices [wordNum + 1]的垃圾值。

+0

嘿,谢谢你的帮助。 –

+0

不客气 –