我正在尝试编写一个获取字符串的函数,然后它将查找第一个单词并返回它,然后从Inputstring中将其删除。所有这些都有效,但是我面临的问题是,一旦有多个空格,它将开始从字符串中的下一个单词中删除字母,这是我不想要的,因为我可能还需要通过调用第二个单词来检查其属性再次起作用。

std::string extractWord (std::string& inspectThis)
{
  std::string firstWord;
  int i = 0;

  for (int count = 0; count < inspectThis.length(); count++) {
    if (isalpha(inspectThis[count]))
      firstWord += inspectThis[count];
    else if (firstWord.length() > 0)
      break;
  }
  int pos = inspectThis.find(firstWord);
  inspectThis.erase(pos, pos + firstWord.length());

  return firstWord;
}



int main() {
  std::string name = "   Help  Final  Test";
  std::cout<<extractWord(name) << std::endl;
  std::cout<<extractWord(name) << std::endl;
  std::cout<<extractWord(name) << std::endl;

  return 0;
}

当我像这样测试我的功能时,输出将是:“Help inal est”

最佳答案

您可以使用std::istringstream而不用担心有多少个空格:

#include <string>
#include <cctype>
#include <sstream>
#include <iostream>

std::string extractWord(std::string& inspectThis)
{
    std::istringstream strm(inspectThis);
    std::string word;
    std::string first_word;
    while (strm >> word)
    {
        if (isalpha(word[0]))
        {
            // This is the first word
            first_word = word;
            std::string newString;

            // get the rest of the words and reset the inspectThis
            while (strm >> word)
                newString += word + " ";
            inspectThis = newString;
            return first_word;
        }
    }
    return "";
}

int main()
{
    std::string name = "   Help  Final  Test";
    std::cout << extractWord(name) << std::endl;
    std::cout << extractWord(name) << std::endl;
    std::cout << extractWord(name) << std::endl;
}

输出:
Help
Final
Test

关于c++ - 逐字获取String Word的函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61387035/

10-11 00:33