Mantid
Loading...
Searching...
No Matches
Strings.h
Go to the documentation of this file.
1// Mantid Repository : https://github.com/mantidproject/mantid
2//
3// Copyright © 2007 ISIS Rutherford Appleton Laboratory UKRI,
4// NScD Oak Ridge National Laboratory, European Spallation Source,
5// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
6// SPDX - License - Identifier: GPL - 3.0 +
7#pragma once
8
9//----------------------------------------------------------------------
10// Includes
11//----------------------------------------------------------------------
12#include "MantidKernel/DllConfig.h"
15#include "MantidKernel/System.h"
16
17#ifndef Q_MOC_RUN
18#include <boost/lexical_cast.hpp>
19#endif
20#include <algorithm>
21#include <iosfwd>
22#include <map>
23#include <set>
24#include <sstream>
25#include <string>
26#include <vector>
27
28namespace Mantid {
29namespace Kernel {
30
34namespace Strings {
35
36//------------------------------------------------------------------------------------------------
53template <typename ITERATOR_TYPE>
54DLLExport std::string simpleJoin(ITERATOR_TYPE begin, ITERATOR_TYPE end, const std::string &separator) {
55 std::ostringstream output;
56 ITERATOR_TYPE it;
57 for (it = begin; it != end;) {
58 output << *it;
59 it++;
60 if (it != end)
61 output << separator;
62 }
63 return output.str();
64}
65
66//------------------------------------------------------------------------------------------------
83template <typename ITERATOR_TYPE>
84DLLExport std::string
85join(ITERATOR_TYPE begin, ITERATOR_TYPE end, const std::string &separator,
86 typename std::enable_if<!(std::is_same<typename std::iterator_traits<ITERATOR_TYPE>::iterator_category,
87 std::random_access_iterator_tag>::value)>::type * = nullptr) {
88 return simpleJoin(begin, end, separator);
89}
90
91//------------------------------------------------------------------------------------------------
110template <typename ITERATOR_TYPE>
111DLLExport std::string
112join(ITERATOR_TYPE begin, ITERATOR_TYPE end, const std::string &separator,
113 typename std::enable_if<(std::is_same<typename std::iterator_traits<ITERATOR_TYPE>::iterator_category,
114 std::random_access_iterator_tag>::value)>::type * = nullptr) {
115
116 // Get max number of threads
117 int nmaxThreads = static_cast<int>(PARALLEL_GET_MAX_THREADS);
118
119 // Define minimum size for using threading
120 int min_size = 500 * nmaxThreads;
121
122 // Get the distance between begining and end
123 int dist = static_cast<int>(std::distance(begin, end));
124
125 if (dist < min_size) {
126
127 // If the input array is small, use the simpler function to avoid
128 // unnecessary overhead from generating the parallel section
129 return simpleJoin(begin, end, separator);
130
131 } else {
132
133 // Allocate vector space
134 std::vector<std::string> output(nmaxThreads);
135 size_t stream_size = 0;
136
137 // Actual number of threads in the current region
138 int nThreads = 1;
139#pragma omp parallel reduction(+ : stream_size)
140 {
141 nThreads = static_cast<int>(PARALLEL_NUMBER_OF_THREADS);
142 int idThread = static_cast<int>(PARALLEL_THREAD_NUMBER);
143
144 // Initialise ostringstream
145 std::ostringstream thread_stream;
146
147/* To make sure the loop is done in the right order, we use schedule(static).
148
149 From the OpenMP documentation:
150 "When schedule(static, chunk_size) is specified, iterations are divided into
151 chunks of size chunk_size, and the chunks are assigned to the threads in the
152 team in a round-robin fashion **in the order of the thread number**."
153
154 "When no chunk_size is specified, the iteration space is divided into chunks
155 that are approximately equal in size, and at most one chunk is distributed
156 to each thread."
157*/
158#pragma omp for schedule(static)
159 for (int i = 0; i < dist; i++) {
160 thread_stream << separator << *(begin + i);
161 }
162 output[idThread] = thread_stream.str();
163 stream_size += output[idThread].length();
164 }
165
166 // Reserve space in memory for output string
167 std::string master_string = output[0].erase(0, separator.length());
168 master_string.reserve(stream_size - separator.length());
169
170 // Concatenate the contributions from the remaning threads
171 // cppcheck-suppress knownConditionTrueFalse
172 for (int i = 1; i < nThreads; i++) {
173 master_string += output[i];
174 }
175
176 return master_string;
177 }
178}
179
180//------------------------------------------------------------------------------------------------
197template <typename ITERATOR_TYPE>
198DLLExport std::string joinCompress(ITERATOR_TYPE begin, ITERATOR_TYPE end, const std::string &separator = ",",
199 const std::string &listSeparator = "-") {
200
201 if (begin == end) {
202 return "";
203 }
204 std::stringstream result;
205
206 ITERATOR_TYPE i = begin;
207 // Always include the first value
208 result << *begin;
209 // move on to the next value
210 ITERATOR_TYPE previousValue = i;
211 ++i;
212
213 std::string currentSeparator = separator;
214 for (; i != end; ++i) {
215 // if it is one higher than the last value
216 if (*i == (*previousValue + 1)) {
217 currentSeparator = listSeparator;
218 } else {
219 if (currentSeparator == listSeparator) {
220 // add the last value that was the end of the list
221 result << currentSeparator;
222 result << *previousValue;
223 currentSeparator = separator;
224 }
225 // add the current value
226 result << currentSeparator;
227 result << *i;
228 }
229 previousValue = i;
230 }
231 // if we have got to the end and part of a list output the last value
232 if (currentSeparator == listSeparator) {
233 result << currentSeparator;
234 result << *previousValue;
235 }
236 return result.str();
237}
239MANTID_KERNEL_DLL std::string shorten(const std::string &input, const size_t max_length);
240
242MANTID_KERNEL_DLL std::string replace(const std::string &input, const std::string &find_what,
243 const std::string &replace_with);
244
246MANTID_KERNEL_DLL std::string replaceAll(std::string const &input, char const to_replace, char const substitute);
247
250MANTID_KERNEL_DLL std::string replaceAll(const std::string &input, const std::string &charStr,
251 const std::string &substitute);
252
254MANTID_KERNEL_DLL std::string toLower(const std::string &input);
255
257MANTID_KERNEL_DLL std::string toUpper(const std::string &input);
258
260MANTID_KERNEL_DLL bool endsWith(std::string const &str, std::string const &suffix);
261
263MANTID_KERNEL_DLL int confirmStr(const std::string &S, const std::string &fullPhrase);
265MANTID_KERNEL_DLL int extractWord(std::string &Line, const std::string &Word, const int cnt = 4);
267MANTID_KERNEL_DLL int endsWithInt(const std::string &word);
268
270MANTID_KERNEL_DLL std::string removeSpace(const std::string &CLine);
272MANTID_KERNEL_DLL std::string fullBlock(const std::string &A);
274MANTID_KERNEL_DLL std::string strip(const std::string &A);
276MANTID_KERNEL_DLL void stripInPlace(std::string &A);
278MANTID_KERNEL_DLL void stripComment(std::string &A);
280MANTID_KERNEL_DLL int isEmpty(const std::string &A);
282MANTID_KERNEL_DLL bool skipLine(const std::string &line);
285MANTID_KERNEL_DLL std::string getLine(std::istream &fh);
288MANTID_KERNEL_DLL void getLine(std::istream &fh, std::string &Line);
290MANTID_KERNEL_DLL std::string peekLine(std::istream &fh);
292MANTID_KERNEL_DLL int getPartLine(std::istream &fh, std::string &Out, std::string &Excess, const int spc = 256);
293
295template <typename T> int convPartNum(const std::string &A, T &out);
296
298template <typename T> int convert(const std::string &A, T &out);
300template <typename T> int convert(const char *A, T &out);
301
303template <typename T> std::string toString(const T &value);
304
306template <typename T> std::string toString(const std::vector<T> &value);
307
309template <typename T> std::string toString(const std::set<T> &value);
310
311template <typename T> int setValues(const std::string &Line, const std::vector<int> &Index, std::vector<T> &Out);
312
314template <typename T> int sectPartNum(std::string &A, T &out);
315
317template <typename T> int section(std::string &A, T &out);
319template <typename T> int section(char *cA, T &out);
320
322template <typename T> int sectionMCNPX(std::string &A, T &out);
323
325MANTID_KERNEL_DLL void writeMCNPX(const std::string &Line, std::ostream &OX);
326
328MANTID_KERNEL_DLL std::vector<std::string> StrParts(const std::string &Ln);
329
331MANTID_KERNEL_DLL std::map<std::string, std::string>
332splitToKeyValues(const std::string &input, const std::string &keyValSep = "=", const std::string &listSep = ",");
333
335template <template <typename T, typename A> class V, typename T, typename A>
336int writeFile(const std::string &Fname, const T &step, const V<T, A> &Y);
337template <template <typename T, typename A> class V, typename T, typename A>
338int writeFile(const std::string &Fname, const V<T, A> &X, const V<T, A> &Y);
339template <template <typename T, typename A> class V, typename T, typename A>
340int writeFile(const std::string &Fname, const V<T, A> &X, const V<T, A> &Y, const V<T, A> &Err);
341
343float getVAXnum(const float A);
344
346MANTID_KERNEL_DLL void readToEndOfLine(std::istream &in, bool ConsumeEOL);
348MANTID_KERNEL_DLL std::string getWord(std::istream &in, bool consumeEOL);
351MANTID_KERNEL_DLL size_t split_path(const std::string &path, std::vector<std::string> &path_components);
352
354MANTID_KERNEL_DLL std::string loadFile(const std::string &filename);
355
357MANTID_KERNEL_DLL int isMember(const std::vector<std::string> &group, const std::string &candidate);
358
361MANTID_KERNEL_DLL std::vector<int> parseRange(const std::string &str, const std::string &elemSep = ",",
362 const std::string &rangeSep = "-");
363
366template <typename Integer> std::vector<std::vector<Integer>> parseGroups(const std::string &str) {
367 std::vector<std::vector<Integer>> groups;
368
369 // Local helper functions.
370 auto translateAdd = [&groups](const std::string &str) {
371 const auto tokens = Kernel::StringTokenizer(
373 std::vector<Integer> currentGroup;
374 currentGroup.reserve(tokens.count());
375 std::transform(tokens.cbegin(), tokens.cend(), std::back_inserter(currentGroup),
376 [](const auto &t) { return boost::lexical_cast<Integer>(t); });
377 groups.emplace_back(std::move(currentGroup));
378 };
379
380 auto translateSumRange = [&groups](const std::string &str) {
381 // add a group with the numbers in the range
382 const auto tokens = Kernel::StringTokenizer(
384 if (tokens.count() != 2)
385 throw std::runtime_error("Malformed range (-) operation.");
386 Integer first = boost::lexical_cast<Integer>(tokens[0]);
387 Integer last = boost::lexical_cast<Integer>(tokens[1]);
388 if (first > last)
389 std::swap(first, last);
390 // add all the numbers in the range to the output group
391 std::vector<Integer> group;
392 group.reserve(last - first + 1);
393 for (Integer i = first; i <= last; ++i)
394 group.emplace_back(i);
395 if (!group.empty())
396 groups.emplace_back(std::move(group));
397 };
398
399 auto translateRange = [&groups](const std::string &str) {
400 // add a group per number
401 const auto tokens = Kernel::StringTokenizer(
403 if (tokens.count() != 2)
404 throw std::runtime_error("Malformed range (:) operation.");
405 Integer first = boost::lexical_cast<Integer>(tokens[0]);
406 Integer last = boost::lexical_cast<Integer>(tokens[1]);
407 if (first > last)
408 std::swap(first, last);
409 // add all the numbers in the range to separate output groups
410 for (Integer i = first; i <= last; ++i) {
411 groups.emplace_back(1, i);
412 }
413 };
414
415 try {
416 // split into comma separated groups, each group potentially containing
417 // an operation (+-:) that produces even more groups.
419 for (const auto &token : tokens) {
420 // Look for the various operators in the string. If one is found then
421 // do the necessary translation into groupings.
422 if (token.find('+') != std::string::npos) {
423 translateAdd(token);
424 } else if (token.find('-') != std::string::npos) {
425 translateSumRange(token);
426 } else if (token.find(':') != std::string::npos) {
427 translateRange(token);
428 } else if (!token.empty()) {
429 // contains a single number, just add it as a new group
430 groups.emplace_back(1, boost::lexical_cast<Integer>(token));
431 }
432 }
433 } catch (boost::bad_lexical_cast &) {
434 throw std::runtime_error("Cannot parse numbers from string: '" + str + "'");
435 }
436
437 return groups;
438}
439
445MANTID_KERNEL_DLL std::string randomString(const size_t len);
446
448MANTID_KERNEL_DLL std::istream &extractToEOL(std::istream &is, std::string &str);
449
457MANTID_KERNEL_DLL std::string strmakef(char const *const fmt, ...);
458
459} // NAMESPACE Strings
460
461} // NAMESPACE Kernel
462
463} // NAMESPACE Mantid
double value
The value of the point.
Definition FitMW.cpp:51
#define PARALLEL_THREAD_NUMBER
#define PARALLEL_NUMBER_OF_THREADS
#define PARALLEL_GET_MAX_THREADS
#define DLLExport
Definitions of the DLLImport compiler directives for MSVC.
Definition System.h:33
Impliments a line.
Definition Line.h:43
@ TOK_IGNORE_EMPTY
ignore empty tokens
@ TOK_TRIM
remove leading and trailing whitespace from tokens
Holds support functions for strings.
MANTID_KERNEL_DLL void stripInPlace(std::string &A)
strip pre/post spaces
Definition Strings.cpp:429
MANTID_KERNEL_DLL std::string removeSpace(const std::string &CLine)
strip all spaces
Definition Strings.cpp:322
MANTID_KERNEL_DLL std::string toLower(const std::string &input)
Converts string to all lowercase.
Definition Strings.cpp:129
MANTID_KERNEL_DLL std::istream & extractToEOL(std::istream &is, std::string &str)
Extract a line from input stream, discarding any EOL characters encountered.
Definition Strings.cpp:1167
int sectPartNum(std::string &A, T &out)
Convert and cut a string.
Definition Strings.cpp:558
MANTID_KERNEL_DLL size_t split_path(const std::string &path, std::vector< std::string > &path_components)
function parses a path, found in input string "path" and returns vector of the folders contributed in...
Definition Strings.cpp:1001
MANTID_KERNEL_DLL int confirmStr(const std::string &S, const std::string &fullPhrase)
determine if a character group exists in a string
Definition Strings.cpp:261
float getVAXnum(const float A)
Convert a VAX number to x86 little eindien.
Definition Strings.cpp:522
DLLExport std::string joinCompress(ITERATOR_TYPE begin, ITERATOR_TYPE end, const std::string &separator=",", const std::string &listSeparator="-")
Join a set or vector of (something that turns into a string) together into one string,...
Definition Strings.h:198
MANTID_KERNEL_DLL std::vector< int > parseRange(const std::string &str, const std::string &elemSep=",", const std::string &rangeSep="-")
Parses a number range, e.g.
Definition Strings.cpp:1101
MANTID_KERNEL_DLL std::string shorten(const std::string &input, const size_t max_length)
Converts long strings into "start ... end".
Definition Strings.cpp:52
int convPartNum(const std::string &A, T &out)
Takes a character string and evaluates the first [typename T] object.
Definition Strings.cpp:670
MANTID_KERNEL_DLL int isMember(const std::vector< std::string > &group, const std::string &candidate)
checks if the candidate is the member of the group
Definition Strings.cpp:1080
DLLExport std::string join(ITERATOR_TYPE begin, ITERATOR_TYPE end, const std::string &separator, typename std::enable_if<!(std::is_same< typename std::iterator_traits< ITERATOR_TYPE >::iterator_category, std::random_access_iterator_tag >::value)>::type *=nullptr)
Join a set or vector of (something that turns into a string) together into one string,...
Definition Strings.h:85
MANTID_KERNEL_DLL std::string replace(const std::string &input, const std::string &find_what, const std::string &replace_with)
Return a string with all matching occurence-strings.
Definition Strings.cpp:72
int section(std::string &A, T &out)
Convert and cut a string.
Definition Strings.cpp:604
MANTID_KERNEL_DLL std::string peekLine(std::istream &fh)
Peek at a line without extracting it from the stream.
Definition Strings.cpp:366
std::vector< std::vector< Integer > > parseGroups(const std::string &str)
Parses unsigned integer groups, e.g.
Definition Strings.h:366
MANTID_KERNEL_DLL std::string replaceAll(std::string const &input, char const to_replace, char const substitute)
Return a string with all occurrences of indicated character replaced by the new character.
Definition Strings.cpp:90
MANTID_KERNEL_DLL std::string fullBlock(const std::string &A)
strip pre/post spaces
Definition Strings.cpp:411
MANTID_KERNEL_DLL bool skipLine(const std::string &line)
Determines if a string starts with a #.
Definition Strings.cpp:439
int sectionMCNPX(std::string &A, T &out)
Convert and cut a string for MCNPX.
Definition Strings.cpp:634
MANTID_KERNEL_DLL std::string loadFile(const std::string &filename)
Loads the entire contents of a text file into a string.
Definition Strings.cpp:26
MANTID_KERNEL_DLL std::vector< std::string > StrParts(std::string, const boost::regex &)
Split a line into component parts.
MANTID_KERNEL_DLL std::string toUpper(const std::string &input)
Converts string to all uppercase.
Definition Strings.cpp:137
MANTID_KERNEL_DLL bool endsWith(std::string const &str, std::string const &suffix)
Checks if string ends with a suffix.
Definition Strings.cpp:145
MANTID_KERNEL_DLL int endsWithInt(const std::string &word)
Get an int from the end of a word.
Definition Strings.cpp:232
MANTID_KERNEL_DLL void writeMCNPX(const std::string &Line, std::ostream &OX)
Write file in standard MCNPX input form.
Definition Strings.cpp:452
MANTID_KERNEL_DLL std::string getLine(std::istream &fh)
Get a line and strip comments Use only for a single call.
Definition Strings.cpp:341
MANTID_KERNEL_DLL void stripComment(std::string &A)
strip trailling comments
Definition Strings.cpp:392
MANTID_KERNEL_DLL int extractWord(std::string &Line, const std::string &Word, const int cnt=4)
Get a word from a string.
Definition Strings.cpp:208
MANTID_KERNEL_DLL std::map< std::string, std::string > splitToKeyValues(const std::string &input, const std::string &keyValSep="=", const std::string &listSep=",")
Splits a string into key value pairs.
Definition Strings.cpp:500
int setValues(const std::string &Line, const std::vector< int > &Index, std::vector< T > &Out)
Call to read in various values in position x1,x2,x3 from the line.
Definition Strings.cpp:875
MANTID_KERNEL_DLL int isEmpty(const std::string &A)
Determines if a string is only spaces.
Definition Strings.cpp:381
int writeFile(const std::string &Fname, const T &step, const V< T, A > &Y)
Write a set of containers to a file.
Definition Strings.cpp:794
DLLExport std::string simpleJoin(ITERATOR_TYPE begin, ITERATOR_TYPE end, const std::string &separator)
Join a set or vector of (something that turns into a string) together into one string,...
Definition Strings.h:54
MANTID_KERNEL_DLL int getPartLine(std::istream &fh, std::string &Out, std::string &Excess, const int spc=256)
get a part of a long line
Definition Strings.cpp:284
std::string toString(const T &value)
Convert values to strings.
Helper class which provides the Collimation Length for SANS instruments.