If you want to find parenthesis with find
of string
it is perfectly possible, and similar to what you were doing:
std::string texto ("Na(CO5(Pt");
std::size_t posicao = texto.find("(");
if (posicao!=std::string::npos){
std::cout << "Parentesis na posição " << posicao << '\n';
}
That will give the exit:
Parentesis na posição 2
The detail is that it finds only the first parentage and from the 0
position. To find the others you need to reuse find
, but using the pos
parameter to only search from the last element found:
std::string texto ("Na(CO5(Pt");
std::size_t posicao = texto.find("(");
while (posicao!=std::string::npos){
std::cout << "Parentesis na posição " << posicao << '\n';
posicao = texto.find("(",posicao + 1); //pesquisar o proximo a partir deste + 1
}
Output:
Parentesis na posição 2
Parentesis na posição 6
See this example in Ideone
If you want to do something more general, as it seemed to you in your code example, you can return all the positions of the parenthesis by means of a function, returning vector<int>
for example:
std::vector<int> obter_posicoes(std::string texto, std::string elemento){
std::vector<int> posicoes;
std::size_t posicao = texto.find(elemento);
while (posicao!=std::string::npos){
posicoes.push_back(posicao);
posicao = texto.find("(",posicao+1);
}
return posicoes;
}
int main (){
std::string texto ("Na(CO5(Pt");
std::vector<int> posicoes = obter_posicoes(texto, "(");
for (auto posicao : posicoes){
std::cout<<posicao<< " ";
}
return 0;
}
This example also in Ideone
Documentation for find