简体   繁体   中英

Split string into parts of equal length c++

I want to iteratively break up a string of arbitrary length into substrings of length = 80 until the size of the final substring is either less than 80 or 0. Assume the string is not divisible by 80 so length of final substring is not necessarily 80. What am I doing wrong here?

#include <string>
#include <math.h>

string sub;

for (int i = 0; i < ceil(str.length()/80); i++) {
            if(str.length()/80 >= 1){
                sub = str.substr(i*80, 80);
            }
            if(str.length()/80 == 0){
                 sub = str.substr(i*80, str.length()%80);
            }
            if(sub.length() <= 0){
                 return;

ceil(str.length()/80) is wrong because it's an integer division. ceil(str.length()/80.0) would work better. It feels wrong to be using floating point arithmetic at all however.

if(str.length()/80 >= 1){
     sub = str.substr(i*80, 80);
}
if(str.length()/80 == 0){
     sub = str.substr(i*80, str.length()%80);
}

Seems OK, but it's unnecessarily complex because it is allowed that the second argument to substr exceeds the length of the string, the rest of the string is selected in that case. So this sub = str.substr(i*80, 80); is all you need to do.

Here's how I would code it

for (size_t i = 0; i < str.size(); i += 80)
{
     string sub = str.substr(i, 80);
     ...
}

Here's how I would code it:

void split(const std::string& str)
{
    const size_t linelength = 80;

    size_t count = str.length() / linelength;
    auto start = str.begin();
    std::string sub;

    for (size_t i = 0; i < count; i++)
    {
        size_t startoffset = i * linelength;
        size_t endoffset = startoffset + linelength;
        sub = std::string(start + startoffset, start + endoffset);
    }
    if (str.length() % linelength)
    {
        sub = std::string(start + count * linelength, str.end());
    }
}

Here is the alternate solution to your problem:

#include <iostream>
#include <string>
#include <bits/stdc++.h> 
using namespace std;


int main() {
    string initial_str =  "";  //your main string
    int len = initial_str.size(); // size of the main string
    vector<string> sub_str; // vector of substrings

    for (int i = 0; i < len; i += 80){
        sub_str.push_back(initial_str.substr(i, 80));
        //cout<< initial_str.substr(i, 5) << endl;
    }

    for (int i = 0; i < sub_str.size(); i++) 
        cout << sub_str[i] << "\n"; 
    return 0;
}

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