Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
StringUtils.cxx
Go to the documentation of this file.
1/// \file ROOT/StringUtils.hxx
2/// \author Jonas Rembser <jonas.rembser@cern.ch>
3/// \date 2021-08-09
4
5/*************************************************************************
6 * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
7 * All rights reserved. *
8 * *
9 * For the licensing terms see $ROOTSYS/LICENSE. *
10 * For the list of contributors see $ROOTSYS/README/CREDITS. *
11 *************************************************************************/
12
13#include "ROOT/StringUtils.hxx"
14#include <algorithm>
15#include <sstream>
16#include <cmath>
17#include <ios>
18#include <cassert>
19
20namespace ROOT {
21
22/// Splits a string at each character in delims.
23/// The behavior mimics `str.split` from Python,
24/// \param[in] str String to tokenise.
25/// \param[in] delims One or more delimiters used to split the string.
26/// \param[in] skipEmpty Strip empty strings from the output.
27std::vector<std::string> Split(std::string_view str, std::string_view delims, bool skipEmpty /* =false */)
28{
29 std::vector<std::string> out;
30
31 std::size_t beg = 0;
32 std::size_t end = 0;
33 while ((end = str.find_first_of(delims, beg)) != std::string::npos) {
34 if (!skipEmpty || end > beg)
35 out.emplace_back(str.substr(beg, end - beg));
36 beg = end + 1;
37 }
38 if (!skipEmpty || str.size() > beg)
39 out.emplace_back(str.substr(beg, str.size() - beg));
40
41 return out;
42}
43
44std::pair<std::string_view, std::string_view> SplitAt(std::string_view str, char splitter)
45{
46 auto pos = str.find(splitter);
47 if (pos == std::string_view::npos)
48 return {str, ""};
49 return {str.substr(0, pos), str.substr(pos + 1)};
50}
51
52/**
53 * \brief Convert (round) a value and its uncertainty to string using one or two significant digits of the error
54 * \param error the error. If the error is negative or zero, only the value is returned with no specific rounding
55 * applied, using std::to_string
56 * \param cutoff should lay between 0 and 9. If first significant digit of error starts with value <= cutoff,
57 * use two significant digits instead of two for rounding. Set this value to zero to always use a
58 * single digit; set this value to 9 to always use two digits.
59 * \param delim delimiter between value and error printed into returned string, leave default for using ROOT's latex
60 * mode.
61 * \return a string with printed rounded value and error separated by "+/-" in ROOT latex mode \note The return
62 * format is `A+-B` using ios::fixed with the proper precision; for very large or very small values of the error, the
63 * format is changed from `A+-B` to (A'+-B')*1eX, with X being multiple of 3, respecting the corresponding precision.
64 * \see https://www.bipm.org/en/doi/10.59161/jcgm100-2008e, https://physics.nist.gov/cuu/Uncertainty/
65 */
66std::string Round(double value, double error, unsigned int cutoff, std::string_view delim)
67{
68 if (error <= 0.) {
69 return std::to_string(value);
70 }
71
72 int error_exponent_base10_rounded = std::floor(std::log10(error));
73 const auto error_magnitude_base10 = std::pow(10., error_exponent_base10_rounded);
74 const auto error_first_digit = static_cast<unsigned int>(error / error_magnitude_base10);
75 assert(error_first_digit > 0 && error_first_digit < 10);
76 if (error_first_digit <= cutoff) {
77 const double rescaled_error = error * std::pow(10., -1. * error_exponent_base10_rounded);
78 if (static_cast<unsigned int>(std::round(rescaled_error * 10) / 10) <= cutoff)
79 error_exponent_base10_rounded--;
80 } else if (cutoff == 0 && error_first_digit == 9) {
81 const double rounded_rescaled_error = std::round(error * std::pow(10., -1. * error_exponent_base10_rounded));
82 const int rounded_rescaled_error_exponent_base10_rounded = std::floor(std::log10(rounded_rescaled_error));
83 const auto rounded_rescaled_error_magnitude_base10 =
84 std::pow(10., rounded_rescaled_error_exponent_base10_rounded);
85 const auto rounded_rescaled_error_first_digit =
86 static_cast<int>(rounded_rescaled_error / rounded_rescaled_error_magnitude_base10);
87 if (rounded_rescaled_error_first_digit == 1)
88 error_exponent_base10_rounded++;
89 }
90 const int factored_out_exponent_base10 = error <= 1e-3 ? static_cast<int>(std::floor(std::log10(error) / 3)) * 3
91 : static_cast<int>(std::log10(error) / 3) * 3;
92
93 std::stringstream result;
94 result.setf(std::ios::fixed);
95 if (error_exponent_base10_rounded - factored_out_exponent_base10 < 0) {
96 result.precision(-error_exponent_base10_rounded + factored_out_exponent_base10);
97 } else {
98 result.precision(0);
99 }
100 if (factored_out_exponent_base10 != 0)
101 result << "(";
102 result << std::round(value * std::pow(10., -error_exponent_base10_rounded)) /
103 std::pow(10., -error_exponent_base10_rounded + factored_out_exponent_base10);
104 result << delim;
105 result << std::round(error * std::pow(10., -error_exponent_base10_rounded)) /
106 std::pow(10., -error_exponent_base10_rounded + factored_out_exponent_base10);
107 if (factored_out_exponent_base10 != 0)
108 result << ")*1e" << factored_out_exponent_base10;
109 return result.str();
110}
111
112std::string WrapString(std::string_view string, std::size_t maxLen, std::size_t indent, std::size_t firstLineMaxLen)
113{
114 if (indent >= maxLen)
115 throw std::invalid_argument("indent cannot be larger than maxLen");
116
117 // the first line gets wrapped to a length of `maxLen - indent`. The idea is that if you're indenting the wrapped
118 // string you might want to append it to a previously-existing one and you might be already in the middle of the
119 // line that you're appending to.
120 auto maxLenUsed = firstLineMaxLen > 0 ? firstLineMaxLen : maxLen - indent;
121
122 std::string result;
123 std::size_t cur = 0;
124 std::string curLine;
125 while (cur < string.size()) {
126 auto pos = string.find_first_of(" \n\t", cur);
127 if (pos == string.npos)
128 break;
129
130 const auto wordSize = pos - cur;
131 // if the word itself is longer than maxLenUsed we must not try to wrap.
132 const bool canWrap = !curLine.empty();
133 // bool wrapped = false;
134 if (canWrap && curLine.size() + wordSize > maxLenUsed) {
135 if (curLine.back() == ' ')
136 curLine.pop_back();
137 result += curLine + '\n';
138 maxLenUsed = maxLen;
139 curLine.clear();
140 curLine.resize(indent, ' ');
141 // wrapped = true;
142 }
143 curLine += string.substr(cur, wordSize);
144
145 cur = pos + 1;
146
147 // whenever we find at least two \n in a row, we preserve them as-is.
148 if (string[pos] == '\n' && pos + 1 < string.size() && string[pos + 1] == '\n') {
149 result += curLine;
150 curLine.clear();
151 curLine.resize(indent, ' ');
152 while (pos < string.size() && string[pos] == '\n') {
153 result += '\n';
154 pos += 1;
155 cur += 1;
156 }
157 cur -= 1;
158 } else if (!(result.empty() && curLine.empty())) {
159 // convert all other separators to space (including single newlines), but skip all leading ones.
160 curLine += ' ';
161 }
162 }
163
164 // append last word
165 const auto wordSize = string.size() - cur;
166 const bool canWrap = !curLine.empty();
167 if (canWrap && curLine.size() + wordSize > maxLenUsed) {
168 if (curLine.back() == ' ')
169 curLine.pop_back();
170 result += curLine + '\n';
171 maxLenUsed = maxLen;
172 curLine.clear();
173 curLine.resize(indent, ' ');
174 }
175 if (cur < string.size())
176 curLine += string.substr(cur);
177 result += curLine;
178
179 return result;
180}
181
182} // namespace ROOT
#define e(i)
Definition RSha256.hxx:103
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
static void indent(ostringstream &buf, int indent_level)
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
std::string WrapString(std::string_view string, std::size_t maxLen, std::size_t indent=0, std::size_t firstLineMaxLen=0)
Splits the given string into multiple lines so that each line is at most maxLen wide.
std::string Round(double value, double error, unsigned int cutoff=1, std::string_view delim="#pm")
Convert (round) a value and its uncertainty to string using one or two significant digits of the erro...
std::vector< std::string > Split(std::string_view str, std::string_view delims, bool skipEmpty=false)
Splits a string at each character in delims.
std::pair< std::string_view, std::string_view > SplitAt(std::string_view str, char splitter)
Given a string str, returns a pair of string views into it: the first containing the substring preced...