User Tools

Site Tools


cpp:string
snippet.cpp
#include <string>
#include <iostream>
#include <memory>
 
struct Foo {
  char foo[3] = {'f','o','o'};
  char e = 42;
  char n = 42;
  char d = 0;
};
 
int main() {
  auto f = std::make_unique<Foo>();
 
 
  std::string s{f->foo, 3};
 
  std::cout << s << std::endl;
  std::cout << f->foo << std::endl;
 
}

prefix search

snippet.cpp
#include <string>
#include <regex>
#include <iostream>
 
struct StringCompareResult {
  std::string input;
  size_t offset;
 
  bool found;
 
  operator bool()
  {
    return found;
  }
 
  std::pair<std::unique_ptr<StringCompareResult>,std::smatch> next(std::regex re)
  {
    auto res = std::make_unique<StringCompareResult>();
    res->input = input.substr(offset);
 
    std::smatch match;
 
    bool found = std::regex_search(res->input, match, re);
 
    res->offset = offset+match[0].str().size();
    res->found = found;
 
    return {std::move(res),match};
  }
 
  StringCompareResult next(const char* search)
  {
    bool found = input.compare(offset, strlen(search), search) == 0;
 
    return {input, offset + strlen(search), found};
  }
};
 
StringCompareResult startsWith(const std::string& input, const char* search)
{
  bool found = input.compare(0, strlen(search), search) == 0;
 
  return {input, strlen(search), found};
}
 
int main()
{
  std::string input{"Hello Fo bar"};
  std::regex re{"(\\w) (\\w)"};
 
  auto h = startsWith(input, "Hello");
 
  if (h)
  {
    std::cout << "found hello" << std::endl;
 
    auto [n, m] = h.next(re);
 
    if (n)
    {
      std::cout << m[0].str() << std::endl;
      std::cout << m[1].str() << std::endl;
    }
  }
 
  return 0;
}
cpp/string.txt · Last modified: by allspark