将字符串迭代器与字符指针进行比较

7

我在一个函数中有一个const char * const字符串。 我想使用它来与字符串中的元素进行比较。

我想遍历这个字符串,然后与char *进行比较。

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

int main()
{

  const char * const pc = "ABC";
  string s = "Test ABC Strings";

  string::iterator i;

  for (i = s.begin(); i != s.end(); ++i)
  {
    if ((*i).compare(pc) == 0)
    {
      cout << "found" << endl;
    }
  }

我该如何将char*解析为与字符串迭代器相匹配的形式?
谢谢。
3个回答

17

看看std::string::find

const char* bar = "bar";
std::string s = "foo bar";

if (s.find(bar) != std::string::npos)
    cout << "found!";

额,我根本没想那么远。你说得对,使用“find”比尝试重新实现它要好得多。+1 - jalf
尽管这是被接受的答案,但它并没有回答所述的问题;@jalf的回答才是。 - fde-capu

12
std::string::iterator it;
char* c;
if (&*it == c)
解引用一个迭代器将得到指向对象的引用。因此,对其进行解引用会给你一个指向该对象的指针。
编辑: 当然,这不是很相关,因为一个更好的方法是完全放弃比较,并依赖于已经存在的find函数来实现你想要的功能。

1

这并不完全是对你问题的回答,但看起来你最好使用std::string::find方法。

像这样:

const char * const pc = "ABC";
string s = "Test ABC Strings";
size_t pos = s.find(pc);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接