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..
Look at std::string::find
:
const char* bar = "bar";
std::string s = "foo bar";
if (s.find(bar) != std::string::npos)
cout << "found!";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With