detect repeated char in c++ string

Asked

Viewed 337 times

0

Hello, I’m trying to make a code to detect the occurrence of parentheses

Na(CO5(Pt

Let’s assume something like, I would have to detect the position of the two parentheses that are in the string.

I tried to use string.find but he always reports me the first parentheses, someone knows some other method?

here’s what I’m trying to.

for (i = 0; i < size(chemform); i++) {
        if (chemform.find("(") != std::string::npos) {

            loc = chemform.find("(", 0);
            start.push_back(loc);
        }
    }

2 answers

1


To find the '(' and its position, go through the entire string, take each character compared to == '(', true case, the position is equal to the loop increment variable.

code:

for(int i =0; i<strlen(suastring); i++){
    if(suastring[i] == '('){
         int posicao = i;
    }
}

1

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.