Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing String Iterator to Char Pointer

Tags:

c++

I have a const char * const string in a function. I want to use this to compare against elements in a string.

I want to iterate through the string and then compare against the 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;
    }
  }

How can I resolve a char* to resolve against a string iterator?

Thanks..

like image 715
donalmg Avatar asked Jan 13 '10 16:01

donalmg


2 Answers

Look at std::string::find:

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

if (s.find(bar) != std::string::npos)
    cout << "found!";
like image 65
Idan K Avatar answered Sep 28 '22 06:09

Idan K


std::string::iterator it;
char* c;
if (&*it == c)

Dereferencing an iterator yields a reference to the pointed-to object. So dereferencing that gives you a pointer to the object.

Edit
Of course, this isn't very relevant as a much better approach is to drop the comparison entirely, and rely on the find function that already exists to do what you want.

like image 31
jalf Avatar answered Sep 28 '22 08:09

jalf