File: stringImproved.h

package info (click to toggle)
seriousproton 2020.01.15%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 720 kB
  • sloc: cpp: 7,666; ansic: 376; php: 59; makefile: 15
file content (630 lines) | stat: -rw-r--r-- 18,227 bytes parent folder | download | duplicates (2)
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
#ifndef STRING_IMPROVED_H
#define STRING_IMPROVED_H

#include <stdlib.h>
#include <string>
#include <limits>
#include <vector>
#include <sstream>
#include <iomanip>

/*
    The improved string class. while this class is not always the most efficient in terms of execution speed.
    It does provide a lot of extra functions which makes it easier to work with strings.
    It implements the same API as python strings where possible. However, python strings are immutable, while C++ strings are mutable.
*/

#define _WHITESPACE " \n\r\t"
class string : public std::string
{
public:
    string() : std::string() {}
    string(const std::string& str) : std::string(str) {}
    string(const char* str) : std::string(str) {}
    string(const char* str, int length) : std::string(str, length) {}

    string(const char c) : std::string()
    {
        push_back(c);
    }

    string(const int nr) : std::string()
    {
        std::ostringstream stream;
        stream << nr;
        *this = stream.str();
    }

    string(const unsigned int nr) : std::string()
    {
        std::ostringstream stream;
        stream << nr;
        *this = stream.str();
    }

    string(const float nr, int decimals = 2) : std::string()
    {
        std::ostringstream stream;
        stream << std::fixed << std::setprecision(decimals);
        stream << nr;
        *this = stream.str();
    }

    static string hex(const int nr)
    {
        std::ostringstream stream;
        stream << std::hex << nr;
        return stream.str();
    }

    /*
        substr works the same as the [start:end] operator in python, allowing negative indexes to get the back of the string.
        It is also garanteed to be safe. So if you request an out of range index, you will get an empty string.
    */
    string substr(const int pos = 0, const int endpos = std::numeric_limits<int>::max()) const
    {
        int start = pos;
        int end = endpos;
        int len = length();
        if (start < 0)
            start = len + start;
        if (end < 0)
            end = len + end;
        if (start < 0)
        {
            end += start;
            start = 0;
        }
        len = std::min(end, len);
        if (end <= start)
        {
            return "";
        }
        return std::string::substr(start, end - start);
    }

    string operator*(const int count)
    {
        if (count <= 0)
            return "";
        string ret;
        for(int n=0; n<count; n++)
            ret += *this;
        return ret;
    }

    /*
        Return a copy of the string S with only its first character capitalized.
    */
    string capitalize()
    {
        return substr(0, 1).upper() + substr(1).lower();
    }

    /*
        Return S centered in a string of length width. Padding is done using the specified fill character (default is a space)
    */
    string center(const int width, const char fillchar=' ') const
    {
        if (width < int(length()))
            return *this;
        int right = width - length();
        int left = right / 2;
        right -= left;
        return string(fillchar) * left + *this + string(fillchar) * right;
    }

    /*
        Return the number of non-overlapping occurrences of substring sub in
        string S[start:end].  Optional arguments start and end are interpreted
        as in slice notation.
    */
    int count(const string sub) const
    {
        if (length() < sub.length())
            return 0;
        int count = 0;
        for(unsigned int n=0; n<=length() - sub.length(); n++)
        {
            if (substr(n, n + sub.length()) == sub)
                count++;
        }
        return count;
    }

    /*
        Return True if S ends with the specified suffix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
    */
    bool endswith(const string suffix) const
    {
        if (suffix.length() == 0)
            return true;
        return substr(-suffix.length()) == suffix;
    }

    /*
        Return a copy of S where all tab characters are expanded using spaces.
        If tabsize is not given, a tab size of 8 characters is assumed.
    */
    string expandtabs(const int tabsize=8) const
    {
        string ret = "";
        int p = 0;
        int t;
        int start = 0;
        int end = find("\r");
        if (find("\n") > -1 && (end == -1 || find("\n") < end))
            end = find("\n");
        while((t = find("\t", p)) > -1)
        {
            while(end != -1 && end < t)
            {
                start = end + 1;
                end = find("\r", start);
                if (find("\n", start) > -1 && (end == -1 || find("\n", start) < end))
                    end = find("\n", start);
            }
            ret += substr(p, t) + string(" ") * (tabsize - ((t - start) % tabsize));
            p = t + 1;
        }
        ret += substr(p);
        return ret;
    }

    /*
        Return the lowest index in S where substring sub is found,
        such that sub is contained within s[start:end].  Optional
        arguments start and end are interpreted as in slice notation.
    */
    int find(const string sub, int start=0) const
    {
        if (sub.length() + start > length() || sub.length() < 1)
            return -1;
        for(unsigned int n=start; n<=length() - sub.length(); n++)
        {
            if(substr(n, n+sub.length()) == sub)
                return n;
        }
        return -1;
    }

    /*
        Return a formatted version of S
    */
    string format(...) const;

    /*
        Return True if all characters in S are alphanumeric
        and there is at least one character in S, False otherwise.
    */
    bool isalnum() const
    {
        int count = 0;
        for(unsigned int n=0; n<length(); n++)
        {
            if (!::isalnum((*this)[n]))
                return false;
            count++;
        }
        return count > 0;
    }

    /*
        Return True if all characters in S are alphabetic
        and there is at least one character in S, False otherwise.
    */
    bool isalpha() const
    {
        int count = 0;
        for(unsigned int n=0; n<length(); n++)
        {
            if (!::isalpha((*this)[n]))
                return false;
            count++;
        }
        return count > 0;
    }

    /*
        Return True if all characters in S are digits
        and there is at least one character in S, False otherwise.
    */
    bool isdigit() const
    {
        int count = 0;
        for(unsigned int n=0; n<length(); n++)
        {
            if (!::isdigit((*this)[n]))
                return false;
            count++;
        }
        return count > 0;
    }

    /*
        Return True if all cased characters in S are lowercase and there is
        at least one cased character in S, False otherwise.
    */
    bool islower() const
    {
        int count = 0;
        for(unsigned int n=0; n<length(); n++)
        {
            if ((*this)[n] == '\n')
                continue;
            if (!::islower((*this)[n]))
                return false;
            count++;
        }
        return count > 0;
    }

    /*
        Return True if all characters in S are whitespace
        and there is at least one character in S, False otherwise.
    */
    bool isspace() const
    {
        int count = 0;
        for(unsigned int n=0; n<length(); n++)
        {
            if (!::isspace((*this)[n]))
                return false;
            count++;
        }
        return count > 0;
    }


    /*
        Return True if S is a titlecased string and there is at least one
        character in S, i.e. uppercase characters may only follow uncased
        characters and lowercase characters only cased ones. Return False
        otherwise.
    */
    bool istitle() const
    {
        int count = 0;
        bool needUpper = true;
        for(unsigned int n=0; n<length(); n++)
        {
            if ((*this)[n] == '\n')
            {
                needUpper = true;
                continue;
            }
            if (::isalpha((*this)[n]))
            {
                if (::isupper((*this)[n]) != needUpper)
                    return false;
                needUpper = false;
            }else{
                needUpper = true;
            }
            count++;
        }
        return count > 0;
    }

    /*
        Return True if all cased characters in S are uppercase and there is
        at least one cased character in S, False otherwise.
    */
    bool isupper() const
    {
        int count = 0;
        for(unsigned int n=0; n<length(); n++)
        {
            if ((*this)[n] == '\n')
                continue;
            if (!::isupper((*this)[n]))
                return false;
            count++;
        }
        return count > 0;
    }


    /*
        Return a string which is the concatenation of the strings in the
        iterable.  The separator between elements is S.
    */
    string join(const std::vector<string> list) const
    {
        string ret;
        for(unsigned int n=0; n<list.size(); n++)
        {
            if (n > 0)
                ret += *this;
            ret += list[n];
        }
        return ret;
    }

    /*
        Return S left-justified in a string of length width. Padding is
        done using the specified fill character (default is a space).
    */
    string ljust(const int width, const char fillchar=' ') const
    {
        if (int(length()) >= width)
            return *this;
        return *this + string(fillchar) * (width - length());
    }

    /*
        Return a copy of the string S converted to lowercase.
    */
    string lower() const
    {
        string ret = *this;
        for(unsigned int n=0; n<length(); n++)
            ret[n] = tolower(ret[n]);
        return ret;
    }

    /*
        Return a copy of the string S with leading whitespace removed.
        If chars is given and not None, remove characters in chars instead.
    */
    string lstrip(const string chars=_WHITESPACE) const
    {
        int start=0;
        while(chars.find(substr(start, start+1)) > -1)
            start++;
        return substr(start);
    }

    /*
        Search for the separator sep in S, and return the part before it,
        the separator itand the part after it.  If the separator is not
        found, return S and two empty strings.
    */
    std::vector<string> partition(const string sep) const;

    /*
        Return a copy of string S with all occurrences of substring
        old replaced by new.  If the optional argument count is
        given, only the first count occurrences are replaced.
    */
    string replace(const string old, const string _new, const int count=-1) const
    {
        if (old.length() < 1)
            return *this;
        
        string result;
        result.reserve(length());
        int start = 0;
        int end = 0;
        for(int amount=0; amount!=count;amount++)
        {
            start = find(old, end);
            if (start < 0)
                break;
            result += substr(end, start) + _new;
            end = start + old.length();
        }
        result += substr(end);
        return result;
    }

    /*
        Return the highest index in S where substring sub is found,
        such that sub is contained within s[start:end].  Optional
        arguments start and end are interpreted as in slice notation.
    */
    int rfind(const string sub, int start=0) const
    {
        if (sub.length() + start > length())
            return -1;
        for(unsigned int n=length() - sub.length(); int(n)>=start; n--)
        {
            if(substr(n, n+sub.length()) == sub)
                return n;
        }
        return -1;
    }

    /*
        Return S right-justified in a string of length width. Padding is
        done using the specified fill character (default is a space)
    */
    string rjust(const int width, const char fillchar=' ') const
    {
        if (int(length()) >= width)
            return *this;
        return string(fillchar) * (width - length()) + *this;
    }

    /*
        Search for the separator sep in S, starting at the end of S, and return
        the part before it, the separator itand the part after it.  If the
        separator is not found, return two empty strings and S.
    */
    std::vector<string> rpartition(const string sep) const;

    /*
        Return a list of the words in the string S, using sep as the
        delimiter string, starting at the end of the string and working
        to the front.  If maxsplit is given, at most maxsplit splits are
        done. If sep is not specified or is None, any whitespace string
        is a separator.
    */
    std::vector<string> rsplit(const string sep=_WHITESPACE, const int maxsplit=-1) const;

    /*
        Return a copy of the string S with trailing whitespace removed.
        If chars is given and not None, remove characters in chars instead.
    */
    string rstrip(const string chars=_WHITESPACE) const
    {
        int end=length()-1;
        while(chars.find(substr(end, end+1)) > -1)
            end--;
        return substr(0, end+1);
    }

    /*
        Return a list of the words in the string S, using sep as the
        delimiter string.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified or is None, any
        whitespace string is a separator and empty strings are removed
        from the result.
    */
    std::vector<string> split(const string sep="", int maxsplit=-1) const
    {
        std::vector<string> res;
        int start = 0;
        if(sep == "")
        {
            res = split(" ", maxsplit);
            for(unsigned int n=0; n<res.size(); n++)
            {
                if (res[n].length() < 1)
                {
                    res.erase(res.begin() + n);
                    n--;
                }
            }
            return res;
        }
        while(maxsplit != 0 && start < int(length()))
        {
            int offset = find(sep, start);
            if (offset < 0)
            {
                res.push_back(substr(start));
                return res;
            }
            res.push_back(substr(start, offset));
            start = offset + sep.length();
            if (maxsplit > 0)
                maxsplit--;
        }
        if (start < int(length()))
            res.push_back(substr(start));
        return res;
    }

    /*
        Return a list of the lines in S, breaking at line boundaries.
        Line breaks are not included in the resulting list unless keepends
        is given and true.
    */
    std::vector<string> splitlines(const bool keepends=false) const;

    /*
        Return True if S starts with the specified prefix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
    */
    bool startswith(const string prefix) const
    {
        return substr(0, prefix.length()) == prefix;
    }

    /*
        Return a copy of the string S with leading and trailing
        whitespace removed.
        If chars is given and not None, remove characters in chars instead.
    */
    string strip(const string chars=_WHITESPACE) const
    {
        return lstrip(chars).rstrip(chars);
    }

    /*
        Return a copy of the string S with uppercase characters
        converted to lowercase and vice versa.
    */
    string swapcase() const
    {
        string ret = *this;
        for(unsigned int n=0; n<length(); n++)
            if (::isupper(ret[n]))
                ret[n] = ::tolower(ret[n]);
            else
                ret[n] = ::toupper(ret[n]);
        return ret;
    }

    /*
        Return a titlecased version of S, i.e. words start with uppercase
        characters, all remaining cased characters have lowercase.
    */
    string title() const
    {
        string ret = *this;
        bool needUpper = true;
        for(unsigned int n=0; n<length(); n++)
        {
            if (::isalpha(ret[n]))
            {
                if (needUpper)
                    ret[n] = ::toupper(ret[n]);
                else
                    ret[n] = ::tolower(ret[n]);
                needUpper = false;
            }else{
                needUpper = true;
            }
        }
        return ret;
    }

    /*
        Return a copy of the string S, where all characters occurring
        in the optional argument deletechars are removed, and the
        remaining characters have been mapped through the given
        translation table, which must be a string of length 256.
    */
    string translate(const string table, const string deletechars="") const;
    /*
        Return a copy of the string S converted to uppercase.
    */
    string upper() const
    {
        string ret = *this;
        for(unsigned int n=0; n<length(); n++)
            ret[n] = toupper(ret[n]);
        return ret;
    }

    /*
        Pad a numeric string S with zeros on the left, to fill a field
        of the specified width.  The string S is never truncated.
    */
    string zfill(const int width) const
    {
        if (int(length()) > width)
            return *this;
        if ((*this)[0] == '-' || (*this)[0] == '+')
            return substr(0, 1) + string("0") * (width - length()) + substr(1);
        return string("0") * (width - length()) + *this;
    }


    /* Convert this string to a number */
    float toFloat() { return atof(c_str()); }
    int toInt(int bits_per_digit=10) { return strtol(c_str(), nullptr, bits_per_digit); }
};
#undef _WHITESPACE

void __stringTest();

namespace std
{
    //Make a specialization of std::hash for this improved string class which uses the same std::hash as std::string.
    //  (no clue why C++ not decides to use the specialization for the base class)
    template <> struct hash< ::string>
    {
        std::size_t operator()(const ::string& k) const
        {
            return hash<std::string>()(k);
        }
    };
}

#endif//STRING_H