简体   繁体   中英

"How do I return the first and last index of a string, into a vector, with C++?

This is a coding problem from Edabit. I am trying to focus on my problem solving skills in C++ specifically.

The problem is to return the first and last index of a char from a string. For every instance of char c (second argument) in std::string word (first argument), I think I need to push (char c) with push_back to an empty string and return first and last index from that empty string. Or could I simply pull the first and last instance of a character from the original string using (for example: std::string word.being() )?

I've included some code below in what I have so far. I'm just stuck on how to implement my idea above with syntax. I think I have the right idea, but not sure how to go about doing so. I don't want an answer exactly, just a guide on what to do next.

std::vector<int> charIndex(std::string word, char c) {
    std::string newWord = "";
    for(int i = 0; i < word.size(); ++i){
        std::string size.push_back[i] = newWord;
        //for every instance of char c in std::string word, I need to 
        //push that (char c) to empty string and return first and last index
        if(newWord[i] ==  )
    }
}

These are examples of expected results:

charIndex("circumlocution", "c") ➞ [0, 8]
The first "c" has index 0, the last "c" has index 8.
charIndex("happy", "h") ➞ [0, 0]
Only one "h" exists, so the first and last index is 0.

Got it!!

vector<int> arr;
arr[0] = word.find_first_of(c);
arr[1] = word.find_last_of(c);
return arr;

Thank you all!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM