mardi 21 février 2023

Parsing Custom String in C++

I have string like:


"../blabla/here_is_same0000:00/0000:00:1A.0/blabla/blabla/blabla"

I want to get 1A.0 part from the string and returning as decimal. These place always comes after the here_is_same0000:00 pattern. Also these places (0000:00:1A.0) not always third place in the given string.

I wrote a code like :

static const std::string test_str1{"../blabla/here_is_same0000:00/0000:00:1A.0/blabla/blabla/blabla"};

std::tuple<int, int> values(const std::string& in)
{
  static const std::string constant_pattern{"here_is_same0000:00"};
  std::size_t found_idx = in.find(constant_pattern);
  if(found_idx == std::string::npos)
  {
    return std::make_tuple(0,0);
  }

  std::string remaining = in.substr(found_idx + constant_pattern.length() + 1, in.length());
  
  found_idx = remaining.find("/");
  if(found_idx == std::string::npos)
  {
    return std::make_tuple(0,0);
  }

  remaining = remaining.substr(0, found_idx);
  found_idx = remaining.find_last_of(":");
  remaining = remaining.substr(found_idx + 1, remaining.length());

  std::stringstream ss(remaining);
  std::string items;
  std::vector<std::string> elements;
  while(std::getline(ss, items, '.'))
  {
    elements.push_back(std::move(items));
  }

  int x;
  std::stringstream ss_convert_x;
  ss_convert_x << std::hex << elements[0];
  ss_convert_x >> x;
  
  int y;
  std::stringstream ss_convert_y;
  ss_convert_y << std::hex << elements[1];
  ss_convert_y >> y;

  std::cout << x <<" "<< y;
  
  return std::make_tuple(x,y);
}

But it looks like bad to me, is there any better way ?

Aucun commentaire:

Enregistrer un commentaire