c++ - How to separate strings based on tokens -


#include <iostream> using namespace std;   void main() {      string target_str =  "1.2.3.4:3333 servertype=simics,arch=x86";      string host_str;      string port_str;      string type_str;      string arch_str;       host_str = target_str.substr(0, target_str.find_first_of(':'));     port_str = target_str.substr(target_str.find_first_of(':')+1);     type_str  = target_str.substr(target_str.find_first_of(':'));     arch_str = target_str.substr(target_str.find_first_of(':')); } 

on completion want following values:

host_str = 1.2.3.4,  port_str = 3333,  type_str = simics  arch_str = x86.  

yes regex works:

std::string target_str =  "1.2.3.4:3333 servertype=simics,arch=x86";  string host_str;  string port_str;  string type_str;  string arch_str;   regex expr("([\\w.]+):(\\d+)\\s+servertype\\s*=\\s*(simics|openocd)(?:\\s*,\\s*| )arch=(x86|x64)");  smatch match;  if (regex_search(target_str, match, expr))  {      cout << "host: " << match[1].str() << endl;      cout << "port: " << match[2].str() << endl;      cout << "type: " << match[3].str() << endl;      cout << "arch: " << match[4].str() << endl;  } 

but unfortunately program has compile on windows , lunix hence have use std strings

here code tokenizes input given std::string , outputs tokens in std::vector<string>. can specify multiple delimiters (in std::string).

#include <iostream> #include <vector> #include <string> #include <stdexcept>   std::vector<std::string>  split(const std::string& str, const std::string& delim){     std::vector<std::string> result;     if (str.empty())         throw std::runtime_error("can not tokenize empty string!");     std::string::const_iterator begin, str_it;     begin = str_it = str.begin();      {         while (delim.find(*str_it) == std::string::npos && str_it != str.end())             str_it++; // find position of first delimiter in str         std::string token = std::string(begin, str_it); // grab token         if (!token.empty()) // empty token when str starts delimiter             result.push_back(token); // push token vector<string>         while (delim.find(*str_it) != std::string::npos && str_it != str.end())             str_it++; // ignore additional consecutive delimiters         begin = str_it; // process remaining tokens         } while (str_it != str.end());     return result; }  int main() {     std::string test_string = ".this is.a.../.simple;;test;;;end";     std::string delim = "; ./"; // string containing delimiters     std::vector<std::string> tokens = split(test_string, delim);                (std::vector<std::string>::const_iterator = tokens.begin();          != tokens.end(); it++)             std::cout << *it << std::endl; } 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -