c++ - 在 std::string 中,是否可以在不使用循环的情况下找到一组字符串中的第一个?

标签 c++ string stl find

在 std::string 中,是否可以在不使用循环的情况下找到一组字符串中的第一个?

例如:

std::string str("aaa bbb ccc ddd eee fff ggg");
std::vector<std::string> vs;
vs.push_back("ccc");
vs.push_back("fff");
size_t pos = 0
pos = str.find(vs, pos);      //< pseudo code

谢谢!

最佳答案

您可以将字符串(使用字符串流)拆分为一个 vector ,然后将 std::find_first_of 与四个迭代器一起使用。

这是一个完整的代码示例

#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
#include <vector>
#include <iterator>

using namespace std;

int main(void)
{
  string str("aaa bbb ccc ddd eee fff ggg");
  vector<string> vs;
  vs.push_back("ccc");
  vs.push_back("fff");
  vector<string> scheck;

  istringstream instr(str);
  copy(istream_iterator<string>(instr),
       istream_iterator<string>(),
       back_inserter(scheck));

  vector<string>::iterator it = find_first_of (scheck.begin(), scheck.end(), vs.begin(), vs.end());
  if (it != scheck.end())
    cout << "first match is: " << *it << endl;

  return 0;
}

关于c++ - 在 std::string 中,是否可以在不使用循环的情况下找到一组字符串中的第一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4334057/

相关文章:

c++ - sizeof() 运算符在 C++ 中做什么

c++ - 排序谓词不传递对索引对象的引用?

c++ - 如何在给定范围内搜索字符串?

c++ - 这个声明是什么意思?异常()抛出()

c++ - 如何用c语言翻译openssl命令pbkdf2?

c# - C# 中 C++ const size_t 的等价物是什么?

c++ - 在 C 接口(interface)中使用 shared_ptr?

android - 从资源中加载语言特定的字符串?

javascript - 如何使用 jQuery 获取、操作和替换文本节点?

c - 字符串比 C 语言中预期的要长