【问题标题】:C++ get iteratorposition of delimiterC ++获取分隔符的迭代器位置
【发布时间】:2014-03-11 09:10:17
【问题描述】:

有人可以帮助我吗,我对字符串迭代器有疑问。

#include <iostream>
#include <string>
#include <vector>

using namespace std;

string s("foo $deli: baa :deli$ no matter")
string deli_open ("$deli:");
string deli_close (":deli$");

string::const_iterator it_begin = s.begin();
string::const_iterator it_end = s.begin();

// calculate won't work because I need the Iterposition! 
size_t found = s.find(deli_open);

if (found != string::npos)
   cout << found << '\n';

// your idea

// return $deli: baa :deli$
for( string::const_iterator i = it_begin; i != it_end; ++i)
{
  cout << (*i) ;
}

cout << endl;

这应该是解决方案:

返回iteratorposition it_begin at "$deli: baa :deli$ no matter"

在“foo $deli: baa :deli$”处返回迭代器位置 it_end

【问题讨论】:

标签: c++ string iterator delimiter


【解决方案1】:

您的要求并不完全清楚 - 我假设您正在寻找一个迭代器,该迭代器指向结束分隔符的末尾。
这可以通过以下步骤完成:

  1. 找到开始分隔符后,从那里搜索结束分隔符。
  2. 找到之后(从该搜索中获得的迭代器将指向它的开头),将迭代器前进 N 个位置,N 是结束分隔符的长度:

    using namespace std;
    int main() {
      string s("foo $deli: baa :deli$ no matter")
      string deli_open ("$deli:");
      string deli_close (":deli$");
    
      size_t startOpenDelim = s.find(deli_open);
      if (startOpenDelim == string::npos)
        cerr << "opening delimiter not found\n";
    
      size_t startCloseDelim = s.find(deli_close, startOpenDelim);
      if (startCloseDelim == string::npos)
        cerr << "closing delimiter not found\n";
    
      size_t endCloseDelim = startCloseDelim + deli_close.length();
    
      string::const_iterator it_begin = s.begin() + startOpenDelim;
      string::const_iterator it_end = s.begin() + endCloseDelim;
    
      cout << string(it_begin, it_end) << endl;
    }
    

【讨论】:

    猜你喜欢
    • 2014-04-01
    • 2021-05-09
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    相关资源
    最近更新 更多