Changeset 18876 for trunk/FACT++


Ignore:
Timestamp:
05/22/17 10:21:01 (7 years ago)
Author:
tbretz
Message:
Added new function 'WordWrap'
Location:
trunk/FACT++/src
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/FACT++/src/tools.cc

    r18826 r18876  
    302302    return charPos<1 ? "" : opt.substr(0, opt[charPos-1]=='#' ? charPos-1 : charPos);
    303303}
     304
     305// --------------------------------------------------------------------------
     306//
     307//! Wraps a given text into a vector of strings with not more than
     308//! max size lines
     309//!
     310vector<string> Tools::WordWrap(string text, const uint16_t &max)
     311{
     312    if (text.size()<max)
     313        return { text };
     314
     315    vector<string> rc;
     316    while (1)
     317    {
     318        // Remove trailing white spaces
     319        const size_t st = text.find_first_not_of(' ');
     320        if (st==string::npos)
     321            break;
     322
     323        text.erase(0, st);
     324        if (text.size()<max)
     325        {
     326            rc.push_back(text);
     327            break;
     328        }
     329
     330        // Last white space - position to break
     331        const size_t ws = text.find_last_of(' ', max);
     332        if (ws==string::npos)
     333        {
     334            rc.push_back(text.substr(0, max));
     335            text.erase(0, max);
     336            continue;
     337        }
     338
     339        // Previous non-whitespace, last position to keep
     340        const size_t ch = text.find_last_not_of(' ', ws);
     341        if (ch==string::npos) // found only white spaces
     342            continue;
     343
     344        rc.push_back(text.substr(0, ch+1));
     345        text.erase(0, ws);
     346    }
     347
     348    return rc;
     349}
  • trunk/FACT++/src/tools.h

    r18188 r18876  
    1818    std::vector<std::string> Split(const std::string &, const std::string &);
    1919    std::string Uncomment(const std::string &opt);
     20
     21    std::vector<std::string> WordWrap(std::string, const uint16_t & = 80);
    2022
    2123    template<typename T>
Note: See TracChangeset for help on using the changeset viewer.