my string contain "hello baby" and i wanted to find the position of the character 'l' which falls in pos 2 and 3. Using string.find("l") return me the position of first "l" found. How can i do a loop to find the position of my next character 'l' in the string?

Recommended Answers

All 2 Replies

The documentation is all you really need, but an example always helps. :)

#include <iostream>
#include <string>
#include <vector>

int main()
{
  typedef std::vector<std::string::size_type> IndexList;

  std::string s = "hello baby";
  IndexList indexes;
  std::string::size_type index = 0;

  while ((index = s.find('l', index)) != std::string::npos) {
    indexes.push_back(index);
    ++index;
  }

  for (IndexList::const_iterator i = indexes.begin(); i != indexes.end(); ++i)
    std::cout << *i << '\n';
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.