首页 > 解决方案 > 逐字获取字符串的函数

问题描述

我正在尝试编写一个获取字符串的函数,然后它将查找第一个单词并将其返回,然后将其从 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”

标签: c++string

解决方案


这篇文章的标题是

逐字获取字符串的函数

因为所有这些都可以通过一个语句来完成,所以不需要单独的函数。使用现代 C++ 语言元素和标准库可以替换所有这些多行代码。

请参见:

#include <iostream>
#include <string>
#include <regex>
#include <algorithm>
#include <iterator>

std::regex word{ R"(\w+)" };


int main() {

    // The string
    std::string name = "   Help  Final  Test";

    // Copy words to std::cout
    std::copy(std::sregex_token_iterator(name.begin(), name.end(), word), {}, std::ostream_iterator<std::string>(std::cout, "\n"));

    return 0;
}

由于程序的简单性(一行代码),我不太确定,该解释什么。因此,我们使用std::copy将源迭代器对之间的某些内容复制到目标迭代器。目标迭代器是std::ostream_iterator,它将(非常简化)为每个源元素调用插入函数 <<。

源元素是std::sregex_token_iterater设计用于迭代字符串中遵循特定模式的元素的元素。模式为 \w+,表示一个或多个字母数字字符。

如果您有任何问题,我很乐意回答。


推荐阅读