detect char repeated in string c ++

0

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

Na(CO5(Pt

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

I tried to use string.find but it always reports me the first parenthesis, does anyone know of any other method?

Here's what I'm trying to do.

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

            loc = chemform.find("(", 0);
            start.push_back(loc);
        }
    }
    
asked by anonymous 14.12.2017 / 03:33

2 answers

1

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

code:

for(int i =0; i<strlen(suastring); i++){
    if(suastring[i] == '('){
         int posicao = i;
    }
}
    
14.12.2017 / 03:42
1

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

    
14.12.2017 / 12:37