Last active
December 24, 2023 06:35
-
-
Save cobalthex/34d9582b77d4849ca2aa1e5bf5112d94 to your computer and use it in GitHub Desktop.
String ops
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <string> | |
| #include <string_view> | |
| #include <optional> | |
| #include <iostream> | |
| struct StringSplitter | |
| { | |
| StringSplitter(char separator, const std::string& string, const std::string& whitespace = " \r\n\t\v") | |
| : m_string(string) | |
| , m_whitespace(whitespace) | |
| , m_next(0) | |
| , m_separator(separator) | |
| { | |
| } | |
| std::optional<std::string_view> GetNext(bool ignoreEmpty = true) | |
| { | |
| if (m_next >= m_string.length()) | |
| { | |
| return std::nullopt; | |
| } | |
| bool allWhitespace = true; | |
| size_t end; | |
| for (end = m_next; end < m_string.length(); ++end) | |
| { | |
| if (m_string[end] == m_separator) | |
| { | |
| if (allWhitespace && ignoreEmpty) | |
| { | |
| m_next = end + 1; | |
| continue; | |
| } | |
| size_t start = m_next; | |
| m_next = end + 1; | |
| return std::optional(m_string.substr(start, end - start)); | |
| } | |
| if (ignoreEmpty && m_whitespace.find(m_string[end]) == std::string_view::npos) | |
| { | |
| allWhitespace = false; | |
| } | |
| } | |
| if (ignoreEmpty && allWhitespace) | |
| { | |
| return std::nullopt; | |
| } | |
| size_t start = m_next; | |
| m_next = end + 1; | |
| return std::optional(std::string_view(m_string).substr(start, end - start)); | |
| } | |
| private: | |
| std::string_view m_string; | |
| std::string_view m_whitespace; | |
| size_t m_next; | |
| char m_separator; | |
| }; | |
| int main() | |
| { | |
| std::string foo = "a;b;c;d;e;f;;g"; | |
| StringSplitter splitter(';', foo); | |
| while (true) | |
| { | |
| auto split = splitter.GetNext(); | |
| if (!split) | |
| { | |
| break; | |
| } | |
| std::cout << split.value() << "\n"; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment