Maher Bisan
Maher Bisan

Reputation: 3

How to find last occurrence of some character in the whole vector<string> then split the string to three separate elements

If I have vector of string vector<string> vec and want to find last occurrence of some character ',' in the complete vector then split the string to three separate elements in the vector in the same place.

vector<string> vec1 = { "string1","str,in,g2" , ",string3 " , "my,target" ," string4" };
vector<string> vec2 = { "string1","str,in,g2" , ",string3 " , "my,tar,get" ," string4" };

I want to convert the vector to:

vector<string> vec1 = { "string1","str,in,g2" , ",string3 " , "my" , "," , "target" , "string4" };
vector<string> vec1 = { "string1","str,in,g2" , ",string3 " , "my,tar" , "," , "get" , "string4" };

is there a short way to that rather than check every string from the end of the vector and copy it to new one ?

I'am using c++11 .

Upvotes: 0

Views: 121

Answers (2)

kesarling
kesarling

Reputation: 2228

Just use reverse iterators:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> vec = { "string1","str,in,g2" , ",string3 " , "my,target" ," string4" };
    for (auto it = vec.rbegin(); it != vec.rend(); it++) {
        std::string str = *it;
        auto comma_pos = std::find(str.rbegin(), str.rend(), ',');
        if (comma_pos != str.rend()) {
            std::string str1(str.begin(), comma_pos.base() - 1);
            std::string str2(",");
            std::string str3(comma_pos.base(), str.end());
            auto insert_it = it.base();
            insert_it = vec.insert(insert_it, str3);
            insert_it = vec.insert(insert_it, str2);
            insert_it = vec.insert(insert_it, str1);
            vec.erase(insert_it - 1);
            break;
        }
    }
}

Upvotes: 0

Sorin
Sorin

Reputation: 11968

Use find to get the last entry that has ',' like this

vector<string> v = ....;
iter = find(v.rbegin(), v.rend(),
            [](const string& s) {return s.find(',') != string::npos;});

After checking you've actually found something split the entry.

// Find the last one, no need to check for not found, we know the string contains 
// a comma. You check above.
auto pos = iter->rfind(','); 
auto first = iter->substr(0, pos);
auto last = iter->substr(pos + 1);

*iter = first;
iter = v.insert(iter + 1, ",");  // No need to extract the comma since it's always a comma.
v.insert(iter + 1, last);

As you can see there's a bit of iterator logic here. Make sure you run with a debugger over a few cases to make sure we got it right.

Upvotes: 1

Related Questions