samedi 25 février 2017

Find Character in String with starting position c++

I am currently having the issue in my code where my find() method does not start at a given position and then "wrap around" the string to find the character. Here is what I have:

int return_encoded_char(string key, string::size_type &start, char C)
  {

    int begin_dist = 0;
    for(string::size_type i = start; i < key.size(); i++){
        if( key[i] == C) {
            start = i;
            return begin_dist;
        }
        begin_dist += 1;
    }
    start = 0;
    return key.size() + 1;
}

I was given inputs to test out this function, and it is this:

2
abcdefghijklmnopqrstuvwxyz
e
7

The function should use abcdefghijklmnopqrstuvwxyz as the key, e as the character to find, and the 7th character in the key as the start position. Then, from the 7th character, look for e (which would be the 23rd).

The output should be: 23 4

How can I make my function start on the "start position" properly? This code currently only works when the inputted start position is 0.

Aucun commentaire:

Enregistrer un commentaire