我正在做一个家庭作业,而且我似乎无法获得正确的功能。有没有人有任何想法,为什么这将无法创建一个由两个空格之间的字符组成的子字符串(字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]));
}
如果's'是'“word1 word2”',那么'wordIndices [0]'将会是'5'。我不认为你想要那样。换句话说,如果没有前导空白字符,'wordIndices [0]'必须设置为'0'。 –
顺便说一句,你可以把'std :: string'当作一个数组来处理,而不需要'at'函数,比如's [z]'。 –