比较字符串迭代器到字符指针
问题描述:
我在函数中有一个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 *来解决字符串迭代器?
谢谢..
答
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)
解引用一个迭代产生一个参考指向的对象。所以解引用给你一个指向对象的指针。
编辑
当然,这是不是一个更好的方法是完全省略了比较,并依靠已经存在于你想要做什么的find
功能密切相关。
答
不完全回答你的问题,但它看起来像你可能与std::string::find
方法更好。
类似的东西:
const char * const pc = "ABC";
string s = "Test ABC Strings";
size_t pos = s.find(pc);
卫生署,我没想到那么远的。你说得对,使用'find'比尝试自己重新实现要好得多。 +1 – jalf 2010-01-13 16:58:23
这个作品,谢谢! – donalmg 2010-01-14 13:48:35