summaryrefslogtreecommitdiff
path: root/euler/source/std/string.cpp
blob: 31c47a540c182faef6f96c21a020e70e4232888a (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
#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;
    }

    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) {
    std::string s = std::move(lhs);
    s.resize(lhs.size() + rhs.size());
    for (size_t i = 0; i < rhs.size(); ++i)
      s[lhs.size() + i] = rhs[i];
    rhs.clear();
    return s;
  }

}