summaryrefslogtreecommitdiff
path: root/euler/source/std/string.cpp
blob: ae397b19d7848b98333df892e615c479a91d1997 (plain) (blame)
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
#include <cctype>
#include <string>

namespace std {

  int stoi(const std::string &str, size_t *pos, int base) {
    //TODO: exceptions

    size_t i = 0;
    while (isspace(str[i]))
      ++i;

    bool is_negative = false;
    if (str[i] == '-') {
      is_negative = true;
      ++i;
    }
    else if (str[i] == '+')
      ++i;

    if ((base == 16 || base == 0) && str[i] == '0' &&
        (str[i + 1] == 'x' || str[i + 1] == 'X')) {
      base = 16;
      i += 2;
    }

    else if ((base == 8 || base == 0) && str[i] == '0') {
      base = 8;
      ++i;
    }

    else if (base == 0)
      base = 10;

    int value = 0;

    while (true) {
      char c = str[i];
      if (c >= '0' && c < '0' + base)
        value = value * base + c - '0';
      else if (c >= 'a' && c < 'a' + base - 10)
        value = value * base + c - 'a' + 10;
      else if (c >= 'A' && c < 'A' + base - 10)
        value = value * base + c - 'A' + 10;
      else
        break;
      ++i;
    }

    if (pos != 0)
      *pos = i;

    return is_negative ? -value : value;

  }

  std::string to_string(int value) {

    int max_place = 1;
    int places = 1;
    while (max_place <= value / 10) {
      max_place *= 10;
      ++places;
    }

    std::string s;
    s.resize(places);

    for (int i = 0; i < places; ++i) {
      s[i] = (value / max_place) % 10 + '0';
      max_place /= 10;
    }

    return s;

  }

  std::string operator +(std::string &&lhs, std::string &&rhs) {
    size_t og_lhs_s = lhs.size();
    std::string s = std::move(lhs);
    s.resize(og_lhs_s + rhs.size());
    for (size_t i = 0; i < rhs.size(); ++i)
      s[og_lhs_s + i] = rhs[i];
    rhs.clear();
    return s;
  }

}