2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2011,2012,2013,2014,2015, by the GROMACS development team, led by
5 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6 * and including many others, as listed in the AUTHORS file in the
7 * top-level source directory and at http://www.gromacs.org.
9 * GROMACS is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the License, or (at your option) any later version.
14 * GROMACS is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with GROMACS; if not, see
21 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * If you want to redistribute modifications to GROMACS, please
25 * consider that scientific software is very special. Version
26 * control is crucial - bugs must be traceable. We will be happy to
27 * consider code for inclusion in the official distribution, but
28 * derived work must not be called official GROMACS. Details are found
29 * in the README & COPYING files - if they are missing, get the
30 * official version at http://www.gromacs.org.
32 * To help us fund GROMACS development, we humbly ask that you cite
33 * the research papers on the package. Check out http://www.gromacs.org.
37 * Implements functions and classes in stringutil.h.
39 * \author Teemu Murtola <teemu.murtola@gmail.com>
40 * \ingroup module_utility
44 #include "stringutil.h"
55 #include "gromacs/utility/gmxassert.h"
60 bool endsWith(const std::string &str, const char *suffix)
62 if (suffix == NULL || suffix[0] == '\0')
66 size_t length = std::strlen(suffix);
67 return (str.length() >= length
68 && str.compare(str.length() - length, length, suffix) == 0);
71 std::string stripSuffixIfPresent(const std::string &str, const char *suffix)
75 size_t suffixLength = std::strlen(suffix);
76 if (suffixLength > 0 && endsWith(str, suffix))
78 return str.substr(0, str.length() - suffixLength);
84 std::string stripString(const std::string &str)
86 std::string::const_iterator start = str.begin();
87 std::string::const_iterator end = str.end();
88 while (start != end && std::isspace(*start))
92 while (start != end && std::isspace(*(end - 1)))
96 return std::string(start, end);
99 std::string formatString(const char *fmt, ...)
102 char staticBuf[1024];
104 std::vector<char> dynamicBuf;
105 char *buf = staticBuf;
107 // TODO: There may be a better way of doing this on Windows, Microsoft
108 // provides their own way of doing things...
112 int n = vsnprintf(buf, length, fmt, ap);
114 if (n > -1 && n < length)
116 std::string result(buf);
127 dynamicBuf.resize(length);
128 buf = &dynamicBuf[0];
132 std::vector<std::string> splitString(const std::string &str)
134 std::vector<std::string> result;
135 std::string::const_iterator currPos = str.begin();
136 const std::string::const_iterator end = str.end();
137 while (currPos != end)
139 while (currPos != end && std::isspace(*currPos))
143 const std::string::const_iterator startPos = currPos;
144 while (currPos != end && !std::isspace(*currPos))
150 result.push_back(std::string(startPos, currPos));
160 * Helper function to identify word boundaries for replaceAllWords().
162 * \returns `true` if the character is considered part of a word.
164 * \ingroup module_utility
166 bool isWordChar(char c)
168 return std::isalnum(c) || c == '-' || c == '_';
172 * Common implementation for string replacement functions.
174 * \param[in] input Input string.
175 * \param[in] from String to find.
176 * \param[in] to String to use to replace \p from.
177 * \param[in] bWholeWords Whether to only consider matches to whole words.
178 * \returns \p input with all occurrences of \p from replaced with \p to.
179 * \throws std::bad_alloc if out of memory.
181 * \ingroup module_utility
184 replaceInternal(const std::string &input, const char *from, const char *to,
187 GMX_RELEASE_ASSERT(from != NULL && to != NULL,
188 "Replacement strings must not be NULL");
189 size_t matchLength = std::strlen(from);
192 size_t matchPos = input.find(from);
193 while (matchPos < input.length())
195 size_t matchEnd = matchPos + matchLength;
198 if (!((matchPos == 0 || !isWordChar(input[matchPos-1]))
199 && (matchEnd == input.length() || !isWordChar(input[matchEnd]))))
201 matchPos = input.find(from, matchPos + 1);
206 result.append(input, inputPos, matchPos - inputPos);
209 matchPos = input.find(from, inputPos);
211 result.append(input, inputPos, matchPos - inputPos);
218 replaceAll(const std::string &input, const char *from, const char *to)
220 return replaceInternal(input, from, to, false);
224 replaceAll(const std::string &input, const std::string &from,
225 const std::string &to)
227 return replaceInternal(input, from.c_str(), to.c_str(), false);
231 replaceAllWords(const std::string &input, const char *from, const char *to)
233 return replaceInternal(input, from, to, true);
237 replaceAllWords(const std::string &input, const std::string &from,
238 const std::string &to)
240 return replaceInternal(input, from.c_str(), to.c_str(), true);
244 /********************************************************************
245 * TextLineWrapperSettings
248 TextLineWrapperSettings::TextLineWrapperSettings()
249 : maxLength_(0), indent_(0), firstLineIndent_(-1),
250 bStripLeadingWhitespace_(false), continuationChar_('\0')
255 /********************************************************************
260 TextLineWrapper::findNextLine(const char *input, size_t lineStart) const
262 size_t inputLength = std::strlen(input);
263 bool bFirstLine = (lineStart == 0 || input[lineStart - 1] == '\n');
264 // Ignore leading whitespace if necessary.
265 if (!bFirstLine || settings_.bStripLeadingWhitespace_)
267 lineStart += std::strspn(input + lineStart, " ");
268 if (lineStart >= inputLength)
274 int indent = (bFirstLine ? settings_.firstLineIndent() : settings_.indent());
275 size_t lastAllowedBreakPoint
276 = (settings_.lineLength() > 0
277 ? std::min(lineStart + settings_.lineLength() - indent, inputLength)
279 // Ignore trailing whitespace.
280 lastAllowedBreakPoint += std::strspn(input + lastAllowedBreakPoint, " ");
281 size_t lineEnd = lineStart;
284 const char *nextBreakPtr = std::strpbrk(input + lineEnd, " \n");
286 = (nextBreakPtr != NULL ? nextBreakPtr - input : inputLength);
287 if (nextBreak > lastAllowedBreakPoint && lineEnd > lineStart)
291 lineEnd = nextBreak + 1;
293 while (lineEnd < lastAllowedBreakPoint && input[lineEnd - 1] != '\n');
294 return (lineEnd < inputLength ? lineEnd : inputLength);
298 TextLineWrapper::findNextLine(const std::string &input, size_t lineStart) const
300 return findNextLine(input.c_str(), lineStart);
304 TextLineWrapper::formatLine(const std::string &input,
305 size_t lineStart, size_t lineEnd) const
307 size_t inputLength = input.length();
308 bool bFirstLine = (lineStart == 0 || input[lineStart - 1] == '\n');
309 // Strip leading whitespace if necessary.
310 if (!bFirstLine || settings_.bStripLeadingWhitespace_)
312 lineStart = input.find_first_not_of(' ', lineStart);
313 if (lineStart >= inputLength)
315 return std::string();
318 int indent = (bFirstLine ? settings_.firstLineIndent() : settings_.indent());
319 bool bContinuation = (lineEnd < inputLength && input[lineEnd - 1] != '\n');
320 // Strip trailing whitespace.
321 while (lineEnd > lineStart && std::isspace(input[lineEnd - 1]))
326 const size_t lineLength = lineEnd - lineStart;
329 return std::string();
331 std::string result(indent, ' ');
332 result.append(input, lineStart, lineLength);
333 if (bContinuation && settings_.continuationChar_ != '\0')
335 result.append(1, ' ');
336 result.append(1, settings_.continuationChar_);
342 TextLineWrapper::wrapToString(const std::string &input) const
345 size_t lineStart = 0;
346 size_t length = input.length();
347 while (lineStart < length)
349 size_t nextLineStart = findNextLine(input, lineStart);
350 result.append(formatLine(input, lineStart, nextLineStart));
351 if (nextLineStart < length
352 || (nextLineStart == length && input[length - 1] == '\n'))
356 lineStart = nextLineStart;
361 std::vector<std::string>
362 TextLineWrapper::wrapToVector(const std::string &input) const
364 std::vector<std::string> result;
365 size_t lineStart = 0;
366 size_t length = input.length();
367 while (lineStart < length)
369 size_t nextLineStart = findNextLine(input, lineStart);
370 result.push_back(formatLine(input, lineStart, nextLineStart));
371 lineStart = nextLineStart;