-2

Split string using loop to specific length sub-units

string str("0123456789asdf");

for (unsigned i = 0; i < str.length(); i += 4) {
    cout << str.substr(i, 4) << endl;
}

so I found this page which is pretty much what I want, but instead of print the values, I need to store them as a vector, this code gives "0123" "4567" "89as" "df", but I need to store them in a vector , also since the last element is "df" I need to attach 2 more "2"s to make it "df22"(i.e. if the desired length is 5 then it should be "01234" "56789" "asdf1" because 5-4=1), is there any way to do that?

Alessandro
  • 742
  • 1
  • 10
  • 34

2 Answers2

-1

Code below:

const unsigned int n = 4;
string str("stackoverflow");
vector<string> strings;

for (unsigned i = 0; i < str.length(); i += n) {
    strings.push_back(str.substr(i, n));
}

//difference from subset length and last string length
unsigned post = n - strings.back().size();
for (unsigned i = 0; i < post; ++i){
    strings.back().append(to_string(post));
}
Naseef Chowdhury
  • 2,357
  • 3
  • 28
  • 52
Alessandro
  • 742
  • 1
  • 10
  • 34
-2
string str("0123456789asdff");
vector<string> strings;
int desire_length = 5;

int ss = str.length()/desire_length;

for (unsigned i = 0; i < str.length(); i += desire_length) {
    strings.push_back(str.substr(i, desire_length));
}

int c_no = desire_length - strings[ss].length();

if(str.length()%desire_length != 0){
    for(int i = 0; i<c_no; i++){
        strings[ss] += std::to_string(c_no);
    }
}

to_string() function is introduced in C++11.

Akash D G
  • 177
  • 1
  • 6
  • 18