couple new features for string wrapper

This commit is contained in:
Metehan Tuncbilek
2024-10-16 14:02:10 +03:00
parent 5256ef8ff3
commit 6d53ff9c76
2 changed files with 95 additions and 1 deletions

View File

@@ -7,6 +7,11 @@
#pragma once
#include <string>
#include <c4/substr.hpp>
#include <c4/substr_fwd.hpp>
#include <c4/format.hpp>
#include <c4/charconv.hpp>
#include <type_traits>
namespace OpenVulkano
{
@@ -43,7 +48,9 @@ namespace OpenVulkano
template<typename T> bool operator!=(const T& other) const { return m_string != other; }
operator std::string() const { return m_string; }
const char* CStr() const { return m_string.c_str(); }
explicit operator std::string_view() const { return m_string; }
const char* CharString() const { return m_string.c_str(); }
const char* Data() { return m_string.data(); }
size_t Length() const { return m_string.length(); }
size_t Size() const { return m_string.size(); }
@@ -52,6 +59,8 @@ namespace OpenVulkano
char& Back() { return m_string.back(); }
void PopBack() { m_string.pop_back(); }
void Clear() { m_string.clear(); }
void Shrink() { m_string.shrink_to_fit(); }
String Substring(size_t start, size_t end) const { return m_string.substr(start, end); }
size_t FindStartIndexOf(const String& str) const { return m_string.find(str); }
@@ -63,6 +72,48 @@ namespace OpenVulkano
return *this;
}
void ToUpper() noexcept
{
for (char& c: m_string)
{
if (c >= 'a' && c <= 'z')
{
c -= 32;
}
}
}
void ToLower() noexcept
{
for (char& c: m_string)
{
if (c >= 'A' && c <= 'Z')
{
c += 32;
}
}
}
// Makes "i am a string" to "I Am A String" also need a better name for the function
void ToUpperStarters()
{
for (size_t i = 0; i < m_string.size(); ++i)
{
if (m_string[i] == ' ')
{
m_string[i + 1] -= 32;
}
}
}
template<typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>> T FromString() const
{
T value;
c4::csubstr str = c4::to_csubstr(m_string.c_str());
c4::from_chars(str, &value);
return value;
}
private:
std::string m_string;
};

View File

@@ -86,4 +86,47 @@ TEST_CASE("String")
REQUIRE(str2 == "World");
REQUIRE(str2 != "Hello");
}
SECTION("Trim")
{
String str1(" Hello World ");
REQUIRE(str1.Trim() == "Hello World");
}
SECTION("FindIndex")
{
String str1("Georg will save us all from our doom");
REQUIRE(str1.FindStartIndexOf("save") == 11);
}
SECTION("Upper/Lower")
{
String str1("Hello World");
str1.ToUpper();
REQUIRE(str1 == "HELLO WORLD");
String str2("Hello World");
str2.ToLower();
REQUIRE(str2 == "hello world");
String str3("Georg will save us all from our doom");
str3.ToUpperStarters();
REQUIRE(str3 == "Georg Will Save Us All From Our Doom");
}
SECTION("Substring")
{
String str1("Hello World");
REQUIRE(str1.Substring(0, 5) == "Hello");
REQUIRE(str1.Substring(6, 11) == "World");
}
SECTION("FromString")
{
String str1("42");
REQUIRE(str1.FromString<int>() == 42);
String str2("42.42");
REQUIRE(str2.FromString<float>() == 42.42f);
}
}