If your C++ compiler is up-to-date (C++23), it's as simple as:
This approach does not create any copies of the substrings, it does not modify the original string, it does not suffer from the reentrancy issues of C functions like strtok, and the use of ranges and string_views minimizes the risk of out-of-bounds accesses or issues with null termination.
Code:
#include <iostream>#include <ranges>#include <string_view>constexpr std::string_view the_string = "This Is My String\nAnother Line\nYet another line";int main() { for (auto substring : std::views::split(the_string, '\n')) std::cout << std::string_view{substring} << '\n';}
Statistics: Posted by tttapa — Sun Mar 31, 2024 2:42 pm