hyprutils/src/string/String.cpp

70 lines
1.6 KiB
C++
Raw Normal View History

2024-06-08 19:37:15 +02:00
#include <algorithm>
#include <hyprutils/string/String.hpp>
using namespace Hyprutils::String;
std::string Hyprutils::String::trim(const std::string& in) {
if (in.empty())
return in;
size_t countBefore = 0;
2024-06-08 19:37:15 +02:00
while (countBefore < in.length() && std::isspace(in.at(countBefore))) {
countBefore++;
}
size_t countAfter = 0;
2024-06-08 19:37:15 +02:00
while (countAfter < in.length() - countBefore && std::isspace(in.at(in.length() - countAfter - 1))) {
countAfter++;
}
std::string result = in.substr(countBefore, in.length() - countBefore - countAfter);
return result;
}
bool Hyprutils::String::isNumber(const std::string& str, bool allowfloat) {
if (str.empty())
return false;
bool decimalParsed = false;
2024-06-08 19:37:15 +02:00
for (size_t i = 0; i < str.length(); ++i) {
const char& c = str.at(i);
if (i == 0 && str.at(i) == '-') {
// only place where we allow -
continue;
}
if (!isdigit(c)) {
if (!allowfloat)
return false;
if (c != '.')
return false;
if (i == 0)
return false;
if (decimalParsed)
2024-06-08 19:37:15 +02:00
return false;
decimalParsed = true;
2024-06-08 19:37:15 +02:00
continue;
}
}
return isdigit(str.back()) != 0;
2024-06-08 19:37:15 +02:00
}
2024-06-08 22:35:40 +02:00
void Hyprutils::String::replaceInString(std::string& string, const std::string& what, const std::string& to) {
if (string.empty())
return;
size_t pos = 0;
while ((pos = string.find(what, pos)) != std::string::npos) {
string.replace(pos, what.length(), to);
pos += to.length();
}
}