splitting string based on length

Aug 3, 2016 at 3:53pm
Hello,

im not sure where to post this - im a beginner but this is a not a easy issue.

I need to write something that passes a value from one program to another. the source program has this description field that is string that has a 550 character length. the destination is a string field that has a length of 254 characters.(it is an invoice so if the description is more than 254 characters I need to insert 2 rows instead of 1)

so for my example lets say the destination is 20 characters and I will use: "I need to write something that passes a value from one program to another." as my source.

I need to take that and break it at the 20 character mark BUT also at the last space so it will look like this:

[i]I need to write
something that
passes a value from
one program to
another.[/I]

ive looked around but I haven't come across anything that is based on if the string length is greater than x to split of last space.

any help is greatly appreciated - thanks!
Aug 3, 2016 at 4:50pm
Something along these lines, perhaps:

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cctype>
#include <sstream>

// invariant: line_sz > length of any single word
std::vector<std::string> split( std::string str, std::size_t line_sz )
{
    if( std::all_of( std::begin(str), std::end(str), [] ( char c ) { return std::isspace(c) ; } ) )
        return {} ; // empty string or string with all spaces, return an empty vector

    std::vector<std::string> result(1) ; // vector containing one empty string

    std::istringstream stm(str) ; // use a string stream to split on white-space
    std::string word ;
    while( stm >> word ) // for each word in the string
    {
        // if this word will fit into the current line, append the word to the current line
        if( ( result.back().size() + word.size() ) <= line_sz ) result.back() += word + ' ' ;

        else
        {
            result.back().pop_back() ; // remove the trailing space at the end of the current line
            result.push_back( word + ' ' ) ; // and place this new word on the next line
        }
    }

    result.back().pop_back() ; // remove the trailing space at the end of the last line
    return result ;
}

int main()
{
    const std::string str = "I need to write something that passes a value from! one program to another. "
                            "This is a test (with a 20 character word) - ottffssentettffssent - end test." ;

    std::cout << "12345678901234567890\n--------------------\n" ;
    for( auto line : split( str, 20 ) ) std::cout << line << '\n' ;
}

http://coliru.stacked-crooked.com/a/8647d9a663904c7a
Last edited on Aug 3, 2016 at 4:53pm
Aug 3, 2016 at 4:52pm
Topic archived. No new replies allowed.