C++ Utilities  4.9.2
Common C++ classes and routines used by my applications such as argument parser, IO and conversion utilities
stringconversion.h
Go to the documentation of this file.
1 #ifndef CONVERSION_UTILITIES_STRINGCONVERSION_H
2 #define CONVERSION_UTILITIES_STRINGCONVERSION_H
3 
4 #include "./binaryconversion.h"
6 
7 #include "../misc/traits.h"
8 
9 #include <cstring>
10 #include <initializer_list>
11 #include <iomanip>
12 #include <list>
13 #include <memory>
14 #include <sstream>
15 #include <string>
16 #include <vector>
17 
18 namespace ConversionUtilities {
19 
28  void operator()(char *stringData)
29  {
30  std::free(stringData);
31  }
32 };
33 
37 typedef std::pair<std::unique_ptr<char[], StringDataDeleter>, std::size_t> StringData;
38 //typedef std::pair<std::unique_ptr<char>, std::size_t> StringData; // might work too
39 
41  const char *fromCharset, const char *toCharset, const char *inputBuffer, std::size_t inputBufferSize, float outputBufferSizeFactor = 1.0f);
42 CPP_UTILITIES_EXPORT StringData convertUtf8ToUtf16LE(const char *inputBuffer, std::size_t inputBufferSize);
43 CPP_UTILITIES_EXPORT StringData convertUtf16LEToUtf8(const char *inputBuffer, std::size_t inputBufferSize);
44 CPP_UTILITIES_EXPORT StringData convertUtf8ToUtf16BE(const char *inputBuffer, std::size_t inputBufferSize);
45 CPP_UTILITIES_EXPORT StringData convertUtf16BEToUtf8(const char *inputBuffer, std::size_t inputBufferSize);
46 CPP_UTILITIES_EXPORT StringData convertLatin1ToUtf8(const char *inputBuffer, std::size_t inputBufferSize);
47 CPP_UTILITIES_EXPORT StringData convertUtf8ToLatin1(const char *inputBuffer, std::size_t inputBufferSize);
48 
49 CPP_UTILITIES_EXPORT void truncateString(std::string &str, char terminationChar = '\0');
50 
64 template <class Container = std::initializer_list<std::string>>
65 typename Container::value_type joinStrings(const Container &strings,
66  const typename Container::value_type &delimiter = typename Container::value_type(), bool omitEmpty = false,
67  const typename Container::value_type &leftClosure = typename Container::value_type(),
68  const typename Container::value_type &rightClosure = typename Container::value_type())
69 {
70  typename Container::value_type res;
71  if (strings.size()) {
72  size_t entries = 0, size = 0;
73  for (const auto &str : strings) {
74  if (!omitEmpty || !str.empty()) {
75  size += str.size();
76  ++entries;
77  }
78  }
79  if (entries) {
80  size += (entries * leftClosure.size()) + (entries * rightClosure.size()) + ((entries - 1) * delimiter.size());
81  res.reserve(size);
82  for (const auto &str : strings) {
83  if (!omitEmpty || !str.empty()) {
84  if (!res.empty()) {
85  res.append(delimiter);
86  }
87  res.append(leftClosure);
88  res.append(str);
89  res.append(rightClosure);
90  }
91  }
92  }
93  }
94  return res;
95 }
96 
100 enum class EmptyPartsTreat {
101  Keep,
102  Omit,
103  Merge
104 };
105 
115 template <class Container = std::list<std::string>>
116 Container splitString(const typename Container::value_type &string, const typename Container::value_type &delimiter,
117  EmptyPartsTreat emptyPartsRole = EmptyPartsTreat::Keep, int maxParts = -1)
118 {
119  --maxParts;
120  Container res;
121  bool merge = false;
122  for (typename Container::value_type::size_type i = 0, end = string.size(), delimPos; i < end; i = delimPos + delimiter.size()) {
123  delimPos = string.find(delimiter, i);
124  if (!merge && maxParts >= 0 && res.size() == static_cast<typename Container::value_type::size_type>(maxParts)) {
125  if (delimPos == i && emptyPartsRole == EmptyPartsTreat::Merge) {
126  if (!res.empty()) {
127  merge = true;
128  continue;
129  }
130  }
131  delimPos = Container::value_type::npos;
132  }
133  if (delimPos == Container::value_type::npos) {
134  delimPos = string.size();
135  }
136  if (emptyPartsRole == EmptyPartsTreat::Keep || i != delimPos) {
137  if (merge) {
138  res.back().append(delimiter);
139  res.back().append(string.substr(i, delimPos - i));
140  merge = false;
141  } else {
142  res.emplace_back(string.substr(i, delimPos - i));
143  }
144  } else if (emptyPartsRole == EmptyPartsTreat::Merge) {
145  if (!res.empty()) {
146  merge = true;
147  }
148  }
149  }
150  return res;
151 }
152 
156 template <typename StringType> bool startsWith(const StringType &str, const StringType &phrase)
157 {
158  if (str.size() < phrase.size()) {
159  return false;
160  }
161  for (auto stri = str.cbegin(), strend = str.cend(), phrasei = phrase.cbegin(), phraseend = phrase.cend(); stri != strend; ++stri, ++phrasei) {
162  if (phrasei == phraseend) {
163  return true;
164  } else if (*stri != *phrasei) {
165  return false;
166  }
167  }
168  return false;
169 }
170 
174 template <typename StringType> bool startsWith(const StringType &str, const typename StringType::value_type *phrase)
175 {
176  for (auto stri = str.cbegin(), strend = str.cend(); stri != strend; ++stri, ++phrase) {
177  if (!*phrase) {
178  return true;
179  } else if (*stri != *phrase) {
180  return false;
181  }
182  }
183  return false;
184 }
185 
190 template <typename StringType> bool containsSubstrings(const StringType &str, std::initializer_list<StringType> substrings)
191 {
192  typename StringType::size_type currentPos = 0;
193  for (const auto &substr : substrings) {
194  if ((currentPos = str.find(substr, currentPos)) == StringType::npos) {
195  return false;
196  }
197  currentPos += substr.size();
198  }
199  return true;
200 }
201 
206 template <typename StringType>
207 bool containsSubstrings(const StringType &str, std::initializer_list<const typename StringType::value_type *> substrings)
208 {
209  typename StringType::size_type currentPos = 0;
210  for (const auto *substr : substrings) {
211  if ((currentPos = str.find(substr, currentPos)) == StringType::npos) {
212  return false;
213  }
214  currentPos += std::strlen(substr);
215  }
216  return true;
217 }
218 
222 template <typename StringType> void findAndReplace(StringType &str, const StringType &find, const StringType &replace)
223 {
224  for (typename StringType::size_type i = 0; (i = str.find(find, i)) != StringType::npos; i += replace.size()) {
225  str.replace(i, find.size(), replace);
226  }
227 }
228 
235 template <typename CharType> constexpr CharType digitToChar(CharType digit)
236 {
237  return digit <= 9 ? (digit + '0') : (digit + 'A' - 10);
238 }
239 
246 template <typename IntegralType, class StringType = std::string,
248 StringType numberToString(IntegralType number, typename StringType::value_type base = 10)
249 {
250  std::size_t resSize = 0;
251  for (auto n = number; n; n /= base, ++resSize)
252  ;
253  StringType res;
254  res.reserve(resSize);
255  do {
256  res.insert(res.begin(), digitToChar<typename StringType::value_type>(number % base));
257  number /= base;
258  } while (number);
259  return res;
260 }
261 
268 template <typename IntegralType, class StringType = std::string, Traits::EnableIf<std::is_integral<IntegralType>, std::is_signed<IntegralType>>...>
269 StringType numberToString(IntegralType number, typename StringType::value_type base = 10)
270 {
271  const bool negative = number < 0;
272  std::size_t resSize;
273  if (negative) {
274  number = -number, resSize = 1;
275  } else {
276  resSize = 0;
277  }
278  for (auto n = number; n; n /= base, ++resSize)
279  ;
280  StringType res;
281  res.reserve(resSize);
282  do {
283  res.insert(res.begin(), digitToChar<typename StringType::value_type>(number % base));
284  number /= base;
285  } while (number);
286  if (negative) {
287  res.insert(res.begin(), '-');
288  }
289  return res;
290 }
291 
300 template <typename FloatingType, class StringType = std::string, Traits::EnableIf<std::is_floating_point<FloatingType>>...>
301 StringType numberToString(FloatingType number, typename StringType::value_type base = 10)
302 {
303  std::basic_stringstream<typename StringType::value_type> ss;
304  ss << std::setbase(base) << number;
305  return ss.str();
306 }
307 
312 template <typename CharType> CharType charToDigit(CharType character, CharType base)
313 {
314  CharType res;
315  if (character >= '0' && character <= '9') {
316  res = character - '0';
317  } else if (character >= 'a' && character <= 'z') {
318  res = character - 'a' + 10;
319  } else if (character >= 'A' && character <= 'Z') {
320  res = character - 'A' + 10;
321  } else {
322  throw ConversionException("The string is no valid number");
323  }
324  if (res >= base) {
325  throw ConversionException("The string is no valid number");
326  }
327  return res;
328 }
329 
337 template <typename IntegralType, class StringType, Traits::EnableIf<std::is_integral<IntegralType>, Traits::Not<std::is_signed<IntegralType>>>...>
338 IntegralType stringToNumber(const StringType &string, typename StringType::value_type base = 10)
339 {
340  IntegralType result = 0;
341  for (const auto &c : string) {
342  if (c == ' ') {
343  continue;
344  }
345  result *= base;
346  result += charToDigit<typename StringType::value_type>(c, base);
347  }
348  return result;
349 }
350 
358 template <typename IntegralType, class StringType, Traits::EnableIf<std::is_integral<IntegralType>, std::is_signed<IntegralType>>...>
359 IntegralType stringToNumber(const StringType &string, typename StringType::value_type base = 10)
360 {
361  auto i = string.begin();
362  auto end = string.end();
363  for (; i != end && *i == ' '; ++i)
364  ;
365  if (i == end) {
366  return 0;
367  }
368  const bool negative = (*i == '-');
369  if (negative) {
370  ++i;
371  }
372  IntegralType result = 0;
373  for (; i != end; ++i) {
374  if (*i == ' ') {
375  continue;
376  }
377  result *= base;
378  result += charToDigit<typename StringType::value_type>(*i, base);
379  }
380  return negative ? -result : result;
381 }
382 
392 template <typename FloatingType, class StringType, Traits::EnableIf<std::is_floating_point<FloatingType>>...>
393 FloatingType stringToNumber(const StringType &string, typename StringType::value_type base = 10)
394 {
395  std::basic_stringstream<typename StringType::value_type> ss;
396  ss << std::setbase(base) << string;
397  FloatingType result;
398  if ((ss >> result) && ss.eof()) {
399  return result;
400  } else {
401  throw ConversionException("The string is no valid number.");
402  }
403 }
404 
412 template <typename IntegralType, class CharType, Traits::EnableIf<std::is_integral<IntegralType>, Traits::Not<std::is_signed<IntegralType>>>...>
413 IntegralType stringToNumber(const CharType *string, unsigned char base = 10)
414 {
415  IntegralType result = 0;
416  for (; *string; ++string) {
417  if (*string == ' ') {
418  continue;
419  }
420  result *= base;
421  result += charToDigit<CharType>(*string, base);
422  }
423  return result;
424 }
425 
433 template <typename IntegralType, class CharType, Traits::EnableIf<std::is_integral<IntegralType>, Traits::Not<std::is_signed<IntegralType>>>...>
434 IntegralType bufferToNumber(const CharType *string, std::size_t size, unsigned char base = 10)
435 {
436  IntegralType result = 0;
437  for (const CharType *end = string + size; string != end; ++string) {
438  if (*string == ' ') {
439  continue;
440  }
441  result *= base;
442  result += charToDigit<CharType>(*string, base);
443  }
444  return result;
445 }
446 
454 template <typename IntegralType, class CharType, Traits::EnableIf<std::is_integral<IntegralType>, std::is_signed<IntegralType>>...>
455 IntegralType stringToNumber(const CharType *string, unsigned char base = 10)
456 {
457  if (!*string) {
458  return 0;
459  }
460  for (; *string && *string == ' '; ++string)
461  ;
462  if (!*string) {
463  return 0;
464  }
465  const bool negative = (*string == '-');
466  if (negative) {
467  ++string;
468  }
469  IntegralType result = 0;
470  for (; *string; ++string) {
471  if (*string == ' ') {
472  continue;
473  }
474  result *= base;
475  result += charToDigit<CharType>(*string, base);
476  }
477  return negative ? -result : result;
478 }
479 
487 template <typename IntegralType, class CharType, Traits::EnableIf<std::is_integral<IntegralType>, std::is_signed<IntegralType>>...>
488 IntegralType bufferToNumber(const CharType *string, std::size_t size, unsigned char base = 10)
489 {
490  if (!size) {
491  return 0;
492  }
493  const CharType *end = string + size;
494  for (; string != end && *string == ' '; ++string)
495  ;
496  if (string == end) {
497  return 0;
498  }
499  const bool negative = (*string == '-');
500  if (negative) {
501  ++string;
502  }
503  IntegralType result = 0;
504  for (; string != end; ++string) {
505  if (*string == ' ') {
506  continue;
507  }
508  result *= base;
509  result += charToDigit<CharType>(*string, base);
510  }
511  return negative ? -result : result;
512 }
513 
523 template <typename T> std::string interpretIntegerAsString(T integer, int startOffset = 0)
524 {
525  char buffer[sizeof(T)];
526  ConversionUtilities::BE::getBytes(integer, buffer);
527  return std::string(buffer + startOffset, sizeof(T) - startOffset);
528 }
529 
530 CPP_UTILITIES_EXPORT std::string dataSizeToString(uint64 sizeInByte, bool includeByte = false);
531 CPP_UTILITIES_EXPORT std::string bitrateToString(double speedInKbitsPerSecond, bool useByteInsteadOfBits = false);
532 CPP_UTILITIES_EXPORT std::string encodeBase64(const byte *data, uint32 dataSize);
533 CPP_UTILITIES_EXPORT std::pair<std::unique_ptr<byte[]>, uint32> decodeBase64(const char *encodedStr, const uint32 strSize);
534 }
535 
536 #endif // CONVERSION_UTILITIES_STRINGCONVERSION_H
CPP_UTILITIES_EXPORT StringData convertUtf8ToUtf16LE(const char *inputBuffer, std::size_t inputBufferSize)
Converts the specified UTF-8 string to UTF-16 (little-endian).
bool startsWith(const StringType &str, const StringType &phrase)
Returns whether str starts with phrase.
void operator()(char *stringData)
Deletes the specified stringData with std::free(), because the memory has been allocated using std::m...
CPP_UTILITIES_EXPORT std::string encodeBase64(const byte *data, uint32 dataSize)
Encodes the specified data to Base64.
IntegralType stringToNumber(const StringType &string, typename StringType::value_type base=10)
Converts the given string to an unsigned number assuming string uses the specified base...
bool containsSubstrings(const StringType &str, std::initializer_list< StringType > substrings)
Returns whether str contains the specified substrings.
The ConversionException class is thrown by the various conversion functions of this library when a co...
CPP_UTILITIES_EXPORT StringData convertUtf16BEToUtf8(const char *inputBuffer, std::size_t inputBufferSize)
Converts the specified UTF-16 (big-endian) string to UTF-8.
CPP_UTILITIES_EXPORT void truncateString(std::string &str, char terminationChar='\0')
Truncates all characters after the first occurrence of the specified terminationChar and the terminat...
StringType numberToString(IntegralType number, typename StringType::value_type base=10)
Converts the given number to its equivalent string representation using the specified base...
std::uint64_t uint64
unsigned 64-bit integer
Definition: types.h:49
The StringDataDeleter struct deletes the data of a StringData instance.
typename std::enable_if< All< Condition... >::value, Detail::Enabler >::type EnableIf
Definition: traits.h:33
std::string interpretIntegerAsString(T integer, int startOffset=0)
Interprets the given integer at the specified position as std::string using the specified byte order...
CPP_UTILITIES_EXPORT StringData convertUtf8ToUtf16BE(const char *inputBuffer, std::size_t inputBufferSize)
Converts the specified UTF-8 string to UTF-16 (big-endian).
EmptyPartsTreat
Specifies the role of empty parts when splitting strings.
CPP_UTILITIES_EXPORT StringData convertUtf8ToLatin1(const char *inputBuffer, std::size_t inputBufferSize)
Converts the specified UTF-8 string to Latin-1.
void findAndReplace(StringType &str, const StringType &find, const StringType &replace)
Replaces all occurences of find with relpace in the specified str.
Contains several functions providing conversions between different data types.
std::uint32_t uint32
unsigned 32-bit integer
Definition: types.h:44
std::pair< std::unique_ptr< char[], StringDataDeleter >, std::size_t > StringData
Type used to return string encoding conversion result.
IntegralType bufferToNumber(const CharType *string, std::size_t size, unsigned char base=10)
Converts the given string of size characters to an unsigned numeric value using the specified base...
CPP_UTILITIES_EXPORT StringData convertUtf16LEToUtf8(const char *inputBuffer, std::size_t inputBufferSize)
Converts the specified UTF-16 (little-endian) string to UTF-8.
CharType charToDigit(CharType character, CharType base)
Returns number/digit of the specified character representation using the specified base...
Container::value_type joinStrings(const Container &strings, const typename Container::value_type &delimiter=typename Container::value_type(), bool omitEmpty=false, const typename Container::value_type &leftClosure=typename Container::value_type(), const typename Container::value_type &rightClosure=typename Container::value_type())
Joins the given strings using the specified delimiter.
CPP_UTILITIES_EXPORT StringData convertString(const char *fromCharset, const char *toCharset, const char *inputBuffer, std::size_t inputBufferSize, float outputBufferSizeFactor=1.0f)
Converts the specified string from one character set to another.
std::uint8_t byte
unsigned byte
Definition: types.h:14
CPP_UTILITIES_EXPORT StringData convertLatin1ToUtf8(const char *inputBuffer, std::size_t inputBufferSize)
Converts the specified Latin-1 string to UTF-8.
Container splitString(const typename Container::value_type &string, const typename Container::value_type &delimiter, EmptyPartsTreat emptyPartsRole=EmptyPartsTreat::Keep, int maxParts=-1)
Splits the given string at the specified delimiter.
CPP_UTILITIES_EXPORT std::string dataSizeToString(uint64 sizeInByte, bool includeByte=false)
Converts the specified data size in byte to its equivalent std::string representation.
#define CPP_UTILITIES_EXPORT
Marks the symbol to be exported by the c++utilities library.
CPP_UTILITIES_EXPORT std::pair< std::unique_ptr< byte[]>, uint32 > decodeBase64(const char *encodedStr, const uint32 strSize)
Decodes the specified Base64 encoded string.
constexpr CharType digitToChar(CharType digit)
Returns the character representation of the specified digit.
CPP_UTILITIES_EXPORT std::string bitrateToString(double speedInKbitsPerSecond, bool useByteInsteadOfBits=false)
Converts the specified bitrate in kbit/s to its equivalent std::string representation.