is_numeric, is_int, is_uint,and is_zero helpers for string.

This commit is contained in:
Relintai 2021-11-09 22:54:04 +01:00
parent 9bc41ad6e4
commit 946c799a3b
2 changed files with 109 additions and 1 deletions

View File

@ -554,6 +554,108 @@ int String::to_int() const {
return atoi(c_str());
}
bool String::is_numeric() const {
if (_size == 0) {
return false;
}
int starti = 0;
if (_data[0] == '-') {
starti += 1;
}
bool had_dot = false;
for (int i = starti; i < _size; ++i) {
if (_data[i] == '.') {
if (!had_dot) {
had_dot = true;
continue;
} else {
return false;
}
}
char c = _data[i];
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
bool String::is_int() const {
if (_size == 0) {
return false;
}
int starti = 0;
if (_data[0] == '-') {
starti += 1;
}
for (int i = starti; i < _size; ++i) {
char c = _data[i];
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
bool String::is_uint() const {
if (_size == 0) {
return false;
}
for (int i = 0; i < _size; ++i) {
char c = _data[i];
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
bool String::is_zero() const {
if (_size == 0) {
return false;
}
int starti = 0;
if (_data[0] == '-') {
starti += 1;
}
bool had_dot = false;
for (int i = starti; i < _size; ++i) {
if (_data[i] == '.') {
if (!had_dot) {
had_dot = true;
continue;
} else {
return false;
}
}
char c = _data[i];
if (c != '0') {
return false;
}
}
return true;
}
uint32_t String::to_uint() const {
return static_cast<uint32_t>(atoll(c_str()));
}

View File

@ -65,6 +65,12 @@ public:
float to_float() const;
double to_double() const;
int to_int() const;
bool is_numeric() const;
bool is_int() const;
bool is_uint() const;
bool is_zero() const;
uint32_t to_uint() const;
std::string to_string() const;
void print() const;