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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
|
// **************************************************************************
// * This file is part of the zenXML project. It is distributed under the *
// * Boost Software License, Version 1.0. See accompanying file *
// * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt. *
// * Copyright (C) ZenJu (zhnmju123 AT gmx DOT de) - All Rights Reserved *
// **************************************************************************
#ifndef STRING_TOOLS_HEADER_213458973046
#define STRING_TOOLS_HEADER_213458973046
#include <cctype> //isspace
#include <cwctype> //iswspace
#include <cstdio> //sprintf
#include <cwchar> //swprintf
#include <algorithm>
#include <cassert>
#include <vector>
#include <sstream>
#include "stl_tools.h"
#include "string_traits.h"
//enhance arbitray string class with useful non-member functions:
namespace zen
{
template <class Char> bool isWhiteSpace(Char ch);
template <class Char> bool isDigit (Char ch); //not exactly the same as "std::isdigit" -> we consider '0'-'9' only!
template <class S, class T> bool startsWith(const S& str, const T& prefix); //both S and T can be strings or char/wchar_t arrays or simple char/wchar_t
template <class S, class T> bool endsWith (const S& str, const T& postfix); //
template <class S, class T> S afterLast (const S& str, const T& ch); //returns the whole string if ch not found
template <class S, class T> S beforeLast (const S& str, const T& ch); //returns empty string if ch not found
template <class S, class T> S afterFirst (const S& str, const T& ch); //returns empty string if ch not found
template <class S, class T> S beforeFirst(const S& str, const T& ch); //returns the whole string if ch not found
template <class S, class T> std::vector<S> split(const S& str, const T& delimiter);
template <class S> void trim(S& str, bool fromLeft = true, bool fromRight = true);
template <class S, class T, class U> void replace ( S& str, const T& oldOne, const U& newOne, bool replaceAll = true);
template <class S, class T, class U> S replaceCpy(const S& str, const T& oldOne, const U& newOne, bool replaceAll = true);
//high-performance conversion between numbers and strings
template <class S, class T, class Num> S printNumber(const T& format, const Num& number); //format a single number using std::snprintf()
template <class S, class Num> S numberTo(const Num& number);
template <class Num, class S > Num stringTo(const S& str);
//string to string conversion: converts string-like type into char-compatible target string class
template <class T, class S> T copyStringTo(const S& str);
//---------------------- implementation ----------------------
template <> inline
bool isWhiteSpace(char ch)
{
//caveat 1: std::isspace() takes an int, but expects an unsigned char
//caveat 2: some parts of UTF-8 chars are erroneously seen as whitespace, e.g. the a0 from "\xec\x8b\xa0" (MSVC)
return static_cast<unsigned char>(ch) < 128 &&
std::isspace(static_cast<unsigned char>(ch)) != 0;
}
template <> inline bool isWhiteSpace(wchar_t ch) { return std::iswspace(ch) != 0; }
template <class Char> inline
bool isDigit(Char ch) //similar to implmenetation of std::::isdigit()!
{
assert_static((IsSameType<Char, char>::value || IsSameType<Char, wchar_t>::value));
return static_cast<Char>('0') <= ch && ch <= static_cast<Char>('9');
}
template <class S, class T> inline
bool startsWith(const S& str, const T& prefix)
{
assert_static(IsStringLike<S>::value && IsStringLike<T>::value);
typedef typename GetCharType<S>::Type CharType;
const size_t pfLength = strLength(prefix);
if (strLength(str) < pfLength)
return false;
const CharType* const strFirst = strBegin(str);
return std::equal(strFirst, strFirst + pfLength,
strBegin(prefix));
}
template <class S, class T> inline
bool endsWith(const S& str, const T& postfix)
{
assert_static(IsStringLike<S>::value && IsStringLike<T>::value);
typedef typename GetCharType<S>::Type CharType;
const size_t strLen = strLength(str);
const size_t pfLen = strLength(postfix);
if (strLen < pfLen)
return false;
const CharType* const cmpFirst = strBegin(str) + strLen - pfLen;
return std::equal(cmpFirst, cmpFirst + pfLen,
strBegin(postfix));
}
//returns the whole string if ch not found
template <class S, class T> inline
S afterLast(const S& str, const T& ch)
{
assert_static(IsStringLike<T>::value);
typedef typename GetCharType<S>::Type CharType;
const size_t chLen = strLength(ch);
const CharType* const strFirst = strBegin(str);
const CharType* const strLast = strFirst + strLength(str);
const CharType* const chFirst = strBegin(ch);
const CharType* iter = search_last(strFirst, strLast,
chFirst, chFirst + chLen);
if (iter == strLast)
return str;
iter += chLen;
return S(iter, strLast - iter);
}
//returns empty string if ch not found
template <class S, class T> inline
S beforeLast(const S& str, const T& ch)
{
assert_static(IsStringLike<T>::value);
typedef typename GetCharType<S>::Type CharType;
const CharType* const strFirst = strBegin(str);
const CharType* const strLast = strFirst + strLength(str);
const CharType* const chFirst = strBegin(ch);
const CharType* iter = search_last(strFirst, strLast,
chFirst, chFirst + strLength(ch));
if (iter == strLast)
return S();
return S(strFirst, iter - strFirst);
}
//returns empty string if ch not found
template <class S, class T> inline
S afterFirst(const S& str, const T& ch)
{
assert_static(IsStringLike<T>::value);
typedef typename GetCharType<S>::Type CharType;
const size_t chLen = strLength(ch);
const CharType* const strFirst = strBegin(str);
const CharType* const strLast = strFirst + strLength(str);
const CharType* const chFirst = strBegin(ch);
const CharType* iter = std::search(strFirst, strLast,
chFirst, chFirst + chLen);
if (iter == strLast)
return S();
iter += chLen;
return S(iter, strLast - iter);
}
//returns the whole string if ch not found
template <class S, class T> inline
S beforeFirst(const S& str, const T& ch)
{
assert_static(IsStringLike<T>::value);
typedef typename GetCharType<S>::Type CharType;
const CharType* const strFirst = strBegin(str);
const CharType* const chFirst = strBegin(ch);
return S(strFirst, std::search(strFirst, strFirst + strLength(str),
chFirst, chFirst + strLength(ch)) - strFirst);
}
template <class S, class T> inline
std::vector<S> split(const S& str, const T& delimiter)
{
assert_static(IsStringLike<T>::value);
typedef typename GetCharType<S>::Type CharType;
std::vector<S> output;
const size_t delimLen = strLength(delimiter);
if (delimLen == 0)
output.push_back(str);
else
{
const CharType* const delimFirst = strBegin(delimiter);
const CharType* const delimLast = delimFirst + delimLen;
const CharType* blockStart = strBegin(str);
const CharType* const strLast = blockStart + strLength(str);
for (;;)
{
const CharType* const blockEnd = std::search(blockStart, strLast,
delimFirst, delimLast);
output.push_back(S(blockStart, blockEnd - blockStart));
if (blockEnd == strLast)
break;
blockStart = blockEnd + delimLen;
}
}
return output;
}
namespace implementation
{
ZEN_INIT_DETECT_MEMBER(append);
//either call operator+=(S(str, len)) or append(str, len)
template <class S, class Char> inline
typename EnableIf<HasMember_append<S>::value>::Type stringAppend(S& str, const Char* other, size_t len) { str.append(other, len); }
template <class S, class Char> inline
typename EnableIf<!HasMember_append<S>::value>::Type stringAppend(S& str, const Char* other, size_t len) { str += S(other, len); }
}
template <class S, class T, class U> inline
S replaceCpy(const S& str, const T& oldOne, const U& newOne, bool replaceAll)
{
assert_static(IsStringLike<T>::value && IsStringLike<U>::value);
typedef typename GetCharType<S>::Type CharType;
const size_t oldLen = strLength(oldOne);
const size_t newLen = strLength(newOne);
S output;
const CharType* strPos = strBegin(str);
const CharType* const strEnd = strPos + strLength(str);
const CharType* const oldBegin = strBegin(oldOne);
const CharType* const newBegin = strBegin(newOne);
for (;;)
{
const CharType* ptr = std::search(strPos, strEnd,
oldBegin, oldBegin + oldLen);
if (ptr == strEnd)
break;
implementation::stringAppend(output, strPos, ptr - strPos);
implementation::stringAppend(output, newBegin, newLen);
strPos = ptr + oldLen;
if (!replaceAll)
break;
}
implementation::stringAppend(output, strPos, strEnd - strPos);
return output;
}
template <class S, class T, class U> inline
void replace(S& str, const T& oldOne, const U& newOne, bool replaceAll)
{
str = replaceCpy(str, oldOne, newOne, replaceAll);
}
template <class S> inline
void trim(S& str, bool fromLeft, bool fromRight)
{
assert(fromLeft || fromRight);
typedef typename GetCharType<S>::Type CharType; //don't use value_type! (wxString, Glib::ustring)
const CharType* const oldBegin = str.c_str();
const CharType* newBegin = oldBegin;
const CharType* newEnd = oldBegin + str.length();
if (fromRight)
while (newBegin != newEnd && isWhiteSpace(newEnd[-1]))
--newEnd;
if (fromLeft)
while (newBegin != newEnd && isWhiteSpace(*newBegin))
++newBegin;
if (newBegin != oldBegin)
str = S(newBegin, newEnd - newBegin); //minor inefficiency: in case "str" is not shared, we could save an allocation and do a memory move only
else
str.resize(newEnd - newBegin);
}
namespace implementation
{
template <class S, class T>
struct CopyStringToString
{
T copy(const S& src) const { return T(strBegin(src), strLength(src)); }
};
template <class S>
struct CopyStringToString<S, S> //perf: we don't need a deep copy if string types match
{
const S& copy(const S& src) const { return src; }
};
}
template <class T, class S> inline
T copyStringTo(const S& str) { return implementation::CopyStringToString<S, T>().copy(str); }
namespace implementation
{
template <class Num> inline
int saferPrintf(char* buffer, size_t bufferSize, const char* format, const Num& number) //there is no such thing as a "safe" printf ;)
{
#if defined _MSC_VER || defined __MINGW32__
return ::_snprintf(buffer, bufferSize, format, number); //by factor 10 faster than "std::snprintf" on Mingw and on par with std::sprintf()!!!
#else
return std::snprintf(buffer, bufferSize, format, number); //C99
#endif
}
template <class Num> inline
int saferPrintf(wchar_t* buffer, size_t bufferSize, const wchar_t* format, const Num& number)
{
#ifdef __MINGW32__
return ::_snwprintf(buffer, bufferSize, format, number); //MinGW doesn't respect ISO C
#else
return std::swprintf(buffer, bufferSize, format, number); //C99
#endif
}
}
template <class S, class T, class Num> inline
S printNumber(const T& format, const Num& number) //format a single number using ::sprintf
{
assert_static(IsStringLike<T>::value);
assert_static((IsSameType<
typename GetCharType<S>::Type,
typename GetCharType<T>::Type>::value));
typedef typename GetCharType<S>::Type CharType;
const int BUFFER_SIZE = 128;
CharType buffer[BUFFER_SIZE];
const int charsWritten = implementation::saferPrintf(buffer, BUFFER_SIZE, format, number);
return charsWritten > 0 ? S(buffer, charsWritten) : S();
}
namespace implementation
{
enum NumberType
{
NUM_TYPE_SIGNED_INT,
NUM_TYPE_UNSIGNED_INT,
NUM_TYPE_FLOATING_POINT,
NUM_TYPE_OTHER,
};
template <class S, class Num> inline
S numberTo(const Num& number, Int2Type<NUM_TYPE_OTHER>) //default number to string conversion using streams: convenient, but SLOW, SLOW, SLOW!!!! (~ factor of 20)
{
typedef typename GetCharType<S>::Type CharType;
std::basic_ostringstream<CharType> ss;
ss << number;
return copyStringTo<S>(ss.str());
}
template <class S, class Num> inline S floatToString(const Num& number, char ) { return printNumber<S>( "%g", static_cast<double>(number)); }
template <class S, class Num> inline S floatToString(const Num& number, wchar_t) { return printNumber<S>(L"%g", static_cast<double>(number)); }
template <class S, class Num> inline
S numberTo(const Num& number, Int2Type<NUM_TYPE_FLOATING_POINT>)
{
return floatToString<S>(number, typename GetCharType<S>::Type());
}
/*
perf: integer to string: (executed 10 mio. times)
std::stringstream - 14796 ms
std::sprintf - 3086 ms
formatInteger - 778 ms
*/
template <class S, class Num> inline
S formatInteger(Num n, bool hasMinus)
{
assert(n >= 0);
typedef typename GetCharType<S>::Type CharType;
const size_t bufferSize = 100; //sufficient for signed 256-bit numbers
CharType buffer[bufferSize]; //it's generally faster to use a buffer than to rely on String::operator+=() (in)efficiency
assert_static(2 + 5 * sizeof(n) / 2 <= bufferSize);
//minimum required chars (+ sign char): 1 + ceil(ln_10 (256^sizeof(n))) =~ 1 + ceil(sizeof(n) * 2.4082) <= 2 + floor(sizeof(n) * 2.5)
size_t startPos = bufferSize;
do
{
buffer[--startPos] = static_cast<char>('0' + n % 10);
n /= 10;
}
while (n != 0);
if (hasMinus)
buffer[--startPos] = static_cast<CharType>('-');
return S(buffer + startPos, bufferSize - startPos);
}
template <class S, class Num> inline
S numberTo(const Num& number, Int2Type<NUM_TYPE_SIGNED_INT>)
{
return formatInteger<S>(number < 0 ? -number : number, number < 0);
}
template <class S, class Num> inline
S numberTo(const Num& number, Int2Type<NUM_TYPE_UNSIGNED_INT>)
{
return formatInteger<S>(number, false);
}
//--------------------------------------------------------------------------------
template <class Num, class S> inline
Num stringTo(const S& str, Int2Type<NUM_TYPE_OTHER>) //default string to number conversion using streams: convenient, but SLOW
{
typedef typename GetCharType<S>::Type CharType;
Num number = 0;
std::basic_istringstream<CharType>(copyStringTo<std::basic_string<CharType> >(str)) >> number;
return number;
}
template <class Num> inline Num stringToFloat(const char* str) { return std::strtod(str, nullptr); }
template <class Num> inline Num stringToFloat(const wchar_t* str) { return std::wcstod(str, nullptr); }
template <class Num, class S> inline
Num stringTo(const S& str, Int2Type<NUM_TYPE_FLOATING_POINT>)
{
return stringToFloat<Num>(strBegin(str));
}
template <class Num, class S>
Num extractInteger(const S& str, bool& hasMinusSign) //very fast conversion to integers: slightly faster than std::atoi, but more importantly: generic
{
typedef typename GetCharType<S>::Type CharType;
const CharType* first = strBegin(str);
const CharType* last = first + strLength(str);
while (first != last && isWhiteSpace(*first)) //skip leading whitespace
++first;
//handle minus sign
hasMinusSign = false;
if (first != last)
{
if (*first == static_cast<CharType>('-'))
{
hasMinusSign = true;
++first;
}
else if (*first == static_cast<CharType>('+'))
++first;
}
Num number = 0;
for (const CharType* iter = first; iter != last; ++iter)
{
const CharType c = *iter;
if (static_cast<CharType>('0') <= c && c <= static_cast<CharType>('9'))
{
number *= 10;
number += c - static_cast<CharType>('0');
}
else
{
//rest of string should contain whitespace only
//assert(std::all_of(iter, last, &isWhiteSpace<CharType>)); -> this is NO assert situation
break;
}
}
return number;
}
template <class Num, class S> inline
Num stringTo(const S& str, Int2Type<NUM_TYPE_SIGNED_INT>)
{
bool hasMinusSign = false; //handle minus sign
const Num number = extractInteger<Num>(str, hasMinusSign);
return hasMinusSign ? -number : number;
}
template <class Num, class S> inline
Num stringTo(const S& str, Int2Type<NUM_TYPE_UNSIGNED_INT>) //very fast conversion to integers: slightly faster than std::atoi, but more importantly: generic
{
bool hasMinusSign = false; //handle minus sign
const Num number = extractInteger<Num>(str, hasMinusSign);
if (hasMinusSign)
{
assert(false);
return 0U;
}
return number;
}
}
template <class S, class Num> inline
S numberTo(const Num& number)
{
typedef Int2Type<
IsSignedInt <Num>::value ? implementation::NUM_TYPE_SIGNED_INT :
IsUnsignedInt<Num>::value ? implementation::NUM_TYPE_UNSIGNED_INT :
IsFloat <Num>::value ? implementation::NUM_TYPE_FLOATING_POINT :
implementation::NUM_TYPE_OTHER> TypeTag;
return implementation::numberTo<S>(number, TypeTag());
}
template <class Num, class S> inline
Num stringTo(const S& str)
{
typedef Int2Type<
IsSignedInt <Num>::value ? implementation::NUM_TYPE_SIGNED_INT :
IsUnsignedInt<Num>::value ? implementation::NUM_TYPE_UNSIGNED_INT :
IsFloat <Num>::value ? implementation::NUM_TYPE_FLOATING_POINT :
implementation::NUM_TYPE_OTHER> TypeTag;
return implementation::stringTo<Num>(str, TypeTag());
}
}
#endif //STRING_TOOLS_HEADER_213458973046
|