c++ - 逐字获取字符串的函数
问题描述
我正在尝试编写一个获取字符串的函数,然后它将查找第一个单词并将其返回,然后将其从 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++ 语言元素和标准库可以替换所有这些多行代码。
请参见:
#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+,表示一个或多个字母数字字符。
如果您有任何问题,我很乐意回答。
推荐阅读
- ansible - Ansible 获取具有相同 IP 的实例
- multithreading - 生产者/转换器/消费者队列的数据结构是什么?
- scala - 将 Scala `Seq[Option[A]]` 转换为 `Option[Seq[A]]`
- jwt - Quarkus - 支持 2 种类型的 jwt 身份验证
- sql-server - SSRS 2019 生成损坏的 PDF
- java - 在 Java 中为 Android 应用程序创建带有插值的自定义图像转换
- html - 为什么我的 flex 布局是水平的而不是垂直的?
- url - Django 的 get_absolute_url 问题
- c - C中的“加号”模板打印更多的列和行
- json-server - 从 json-server 中的浏览器获取请求的问题