Porytiles
Loading...
Searching...
No Matches
string_utils.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <ranges>
4#include <regex>
5#include <string>
6
7#include "fmt/format.h"
8
10
11namespace porytiles2 {
12
25inline bool check_full_string_match(const std::string &str, const std::string &pattern)
26{
27 try {
28 const std::regex re{pattern};
29 return std::regex_match(str, re);
30 }
31 catch (const std::regex_error &e) {
32 panic(fmt::format("regex error: {}", e.what()));
33 }
34}
35
45inline void trim(std::string &string)
46{
47 // Trim blank space from the beginning
48 string.erase(
49 string.begin(), std::ranges::find_if(string, [](const unsigned char ch) { return !std::isspace(ch); }));
50
51 // Trim blank space from the end
52 string.erase(
53 std::ranges::find_if(string.rbegin(), string.rend(), [](const unsigned char ch) { return !std::isspace(ch); })
54 .base(),
55 string.end());
56}
57
70inline std::vector<std::string> split(std::string input, const std::string &delimiter)
71{
72 std::vector<std::string> result;
73 size_t pos;
74 while ((pos = input.find(delimiter)) != std::string::npos) {
75 std::string token = input.substr(0, pos);
76 result.push_back(token);
77 input.erase(0, pos + delimiter.length());
78 }
79 result.push_back(input);
80 return result;
81}
82
93inline std::string &trim_line_ending(std::string &line)
94{
95 while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) {
96 line.pop_back();
97 }
98 return line;
99}
100
112inline std::string trim_line_ending(const std::string &line)
113{
114 std::string result = line;
115 while (!result.empty() && (result.back() == '\r' || result.back() == '\n')) {
116 result.pop_back();
117 }
118 return result;
119}
120
121} // namespace porytiles2
void panic(const StringViewSourceLoc &s)
Unconditionally terminates the program with a panic message.
Definition panic.hpp:53
void trim(std::string &string)
Removes leading and trailing whitespace from a string in-place.
std::vector< std::string > split(std::string input, const std::string &delimiter)
Splits a string into tokens based on a delimiter.
bool check_full_string_match(const std::string &str, const std::string &pattern)
Checks if a string fully matches a regular expression pattern.
std::string & trim_line_ending(std::string &line)
Removes line ending characters from a string in-place.