Finding Character in String with starting point

Hey everyone, I am trying to figure out how to make it so when a string is inputted into the function along with a start position and character to find, the function will go to the string and look for the character depending on the start position. I was given 3 cases to test out, and 2 of the 3 work. Here is the code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
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;
}


• if the character C is found in key:
o returns an integer that represents the distance required to find the provided character
C in the key (including wrap around).
o otherwise it returns key.size() + 1.
• updates start to the new index (passed by reference)
o if the character is not found, start is updated to 0.
• returns the integer

Here is the sample case I was given:
1
2
3
4
2
abcdefghijklmnopqrstuvwxyz
e
7


The answer I was getting:
 
27 0 


Output I should be getting:
 
23 4 


Thank you in advance for any help!
You need to sub-string the key string and then apply the find method of the string class, here's an outline:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>

int main()
{
    std::string myString = "HelloWorld \n";

    auto itr = myString.substr(2).find('H');
    if(itr != std::string::npos)   std::cout << "Found at " << itr;
    std::cout << "\nNot found in the (sub) string \n";
}


How would I make it so the find method would start on the "start" position which is given through string::size_type &start?


The find() method is suppose to start on the 7th character in this case and then wrap around and find e which would be in the 23rd place from the 7th character.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>

int main()
{
    std::string myString = "HelloWorld";
    std::cout << myString.size() << "\n";
    std::cout << myString.substr(2) << "\n";
    std::cout << myString.substr(2).size() << "\n";

    auto itr = myString.substr(2).find('H');
    if(itr != std::string::npos)
    {
        std::cout << "Found at " << itr;
    }
    else
    {
        std::string temp{myString.begin(), myString.begin()+2};
        std::cout << temp << "\n";
        auto itr = temp.find('H');
        if (itr != std::string::npos)
        {
            std::cout << "found at " << myString.substr(2).size() + itr + 1;
        }
    }
}
edit: you should also cover the possibility that the character is not found in the string, declare a bool match = false before entering the loops and set match == true in either loop if found and check the value of match before exiting the program
Last edited on
Topic archived. No new replies allowed.