在std :: string中,是否可以找到一组字符串中的第一个而不使用循环? [英] Inside a std::string, is it possible to find the first of a set of strings without using a loop?

查看:138
本文介绍了在std :: string中,是否可以找到一组字符串中的第一个而不使用循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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); //<


解决方案

您可以将字符串(使用stringstream)拆分为一个向量,然后使用 std :: find_first_of >

这是一个完整的代码示例

  #include< iostream& 
#include< string>
#include< algorithm>
#include< sstream>
#include< vector>
#include
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>检查;

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(),vsend());
if(it!= scheck.end())
cout<< 第一匹配是:< * it< endl;

return 0;
}


Inside a std::string, is it possible to find the first of a set of strings without using a loop?

E.g.:

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

Thank you!

解决方案

You could split the string (using a stringstream) into a vector and then use std::find_first_of with the four iterators.

Here is a complete code example

#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;
}

这篇关于在std :: string中,是否可以找到一组字符串中的第一个而不使用循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆