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.
#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' ;
}