Files
cpp-course/modules/04_arrays_and_strings/src/std_string.cpp
T
2026-08-15 16:55:46 +03:00

47 lines
1.4 KiB
C++

#include "std_string.hpp"
#include <algorithm>
#include <locale>
#include <ranges>
#include <sstream>
namespace arrays {
auto to_uppercase(const std::string &text) -> std::string {
// Returns copy of the string without mutating the original string
auto s = std::string{text};
auto c_to_upper = [](const unsigned char c) { return std::toupper(c); };
std::ranges::transform(s, s.begin(), c_to_upper);
return s;
}
auto trim(const std::string& text) -> std::string {
// Returns a trimmed copy of the string
auto s = std::string{text};
auto is_not_space = [](const unsigned char c) { return !std::isspace(c); };
const auto first = std::ranges::find_if(s, is_not_space);
const auto last = std::ranges::find_if(s.rbegin(), s.rend(), is_not_space).base();
s.erase(last, s.end());
s.erase(s.begin(), first);
return s;
}
auto replace_all(const std::string &text, const char from, const char to) -> std::string {
// This one also copies the string
auto s = std::string{text};
std::ranges::replace(s, from, to);
return s;
}
auto starts_with(const std::string& text, const std::string& prefix) -> bool {
// Since C++20 you can use std::string::starts_with, but anyways.
if (text.size() < prefix.size()) return false;
// uz -> unsigned size_t
for (auto idx = 0uz; idx < prefix.size(); ++idx) {
if (text[idx] != prefix[idx]) return false;
}
return true;
}
} // namespace arrays