Move History

Rooted by: String Split
Fork Selected
  • Description

    Probably would be considered less clean than the parent, but also faster by avoiding streams.

    Code
    #include <string>
    #include <vector>
    
    auto split(const std::string& str, char sep) {
      auto result = std::vector<std::string>{};
      std::string::size_type pos = 0, pos2 = 0;
      
      while ((pos2 = str.find(sep, pos)) != std::string::npos) {
        result.push_back(str.substr(pos, pos2 - pos));
        pos = pos2 + 1;
      }
      result.push_back(str.substr(pos));
      return result;
    }
    
    
    Test Cases
    // TODO: Replace examples and use TDD by writing your own tests
    
    Describe(any_group_name_you_want)
    {
        It(should_do_something)
        {
            Assert::That(split("Hello World", ' '), Equals(std::vector<std::string>{"Hello", "World"}));
            Assert::That(split("John-brings-his-cat", '-'), Equals(std::vector<std::string>{"John","brings","his","cat"}));
        }
    };
    
  • Code
    • #include <string>
    • #include <sstream>
    • #include <vector>
    • auto split(const std::string& str, char sep) {
    • auto result = std::vector<std::string>{};
    • auto stream = std::stringstream(str);
    • auto buffer = std::string{};
    • while (std::getline(stream, buffer, sep)) result.emplace_back(buffer);
    • std::string::size_type pos = 0, pos2 = 0;
    • while ((pos2 = str.find(sep, pos)) != std::string::npos) {
    • result.push_back(str.substr(pos, pos2 - pos));
    • pos = pos2 + 1;
    • }
    • result.push_back(str.substr(pos));
    • return result;
    • }