If you want to find parenthesis with the find
of string
is perfectly possible, and similar to what I was 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 only finds the first parentesis and from the position 0
. To find others you need to use again find
, but using the parameter pos
to only search from the last found widget:
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
}
Exit:
Parentesis na posição 2
Parentesis na posição 6
See this example in Ideone
If you want to do something more General, as I thought in your example of code, you can return all parentesis positions by means of a function, returning a 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 the find