tags:

views:

122

answers:

3

Hi,

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..

A: 
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.

jalf
+8  A: 

Look at std::string::find:

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

if (s.find(bar) != std::string::npos)
    cout << "found!";
Idan K
Doh, I didn't think that far at all. You're right, using `find` is a far better approach than trying to reimplement it yourself. +1
jalf
this works, thanks!
donalmg
A: 

Not exactly an answer to your question, but it looks like you might be better off with std::string::find method.

Something like that:

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