aboutsummaryrefslogtreecommitdiff
path: root/Source/ablastr/utils/text/StringUtils.cpp
blob: 7409fa7e7a3775890ef8ff45d5427c5af06ebaa9 (plain) (blame)
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
42
43
44
45
46
47
48
49
50
51
52
53
/* Copyright 2022 Andrew Myers, Luca Fedeli, Maxence Thevenet
 * Revathi Jambunathan
 *
 * This file is part of WarpX.
 *
 * License: BSD-3-Clause-LBNL
 */

#include "StringUtils.H"

#include <sstream>

std::vector<std::string>
ablastr::utils::text::automatic_text_wrap(
    const std::string& text, const int max_line_length){

    auto ss_text = std::stringstream{text};
    auto wrapped_text_lines = std::vector<std::string>{};

    std::string line;
    while(std::getline(ss_text, line,'\n')){

        auto ss_line = std::stringstream{line};
        int counter = 0;
        std::stringstream ss_line_out;
        std::string word;

        while (ss_line >> word){
            const auto wlen = static_cast<int>(word.length());

            if(counter == 0){
                ss_line_out << word;
                counter += wlen;
            }
            else{
                if (counter + wlen < max_line_length){
                    ss_line_out << " " << word;
                    counter += (wlen+1);
                }
                else{
                    wrapped_text_lines.push_back(ss_line_out.str());
                    ss_line_out.str("");
                    ss_line_out << word;
                    counter = wlen;
                }
            }
        }

        wrapped_text_lines.push_back(ss_line_out.str());
    }

    return wrapped_text_lines;
}