String zerlegen
-
Hey ihr,
ich muss einen std::string der Form:
std::string address= "TYPE=dom,home,postal,parcel:;;123 Main Street;Any Town;CA;91921-1234";an den ";" zerlegen. Klappt fast
mit:while( (start = address.find_first_not_of(";", start)) != std::string::npos) { end = address.find_first_of(";", start); tokens.push_back( address.substr(start, end - start) ); start = end; }Allerdings bekomme ich fuer ;; keine Tokens. Aber ich braeuchte da eben ein leeres Token. Es fehlt also noch was. Ich koennte jetzt noch die ";" durch ein " ;" ersetzen, aber das muss doch auch eleganter gehen.
Die andere Moeglichkeit waere es getline zu benutzen:
std::istringstream is(data); getline(is,name,';'); getline(is,street,';'); getline(is,city, ';'); usw.Was haltet ihr davon? Mir wuerde die erste Loesung besser gefallen...
Gruss
Max
-
ich hab in nem andern thread ("explode" war das thema) ne func dafür von muir gepostet.
benutz doch die.in deinem fall dann so:
... std::string abc = "bsp"; std::vector<std::string> def; explode(abc, ';', def); ...Mfg Shade37337
-
hier is der code:
/* Copyright (c) by Shade37337, Nanosoft It's free to use this code in non-commercial projects or for education. You're not allowed to use this code for commercial products. You mustn't misrepresent this Code if you ever used it. You musn't modify this code. And and at last You musn't remove the Copyright notation and You're not allowed to remove this license notation (Sorry for my bad english, i'm still learning it....) */ void explode(const std::string& text, const char& token, std::vector<std::string>& result) { std::string strSub; std::vector<std::string> res2; std::string::size_type last = 0; std::string::size_type temp = text.find_first_of(token, last); while (temp != std::string::npos) { strSub = text.substr(last, temp - last); if (!strSub.empty()) { res2.push_back(strSub); } last = temp + 1; temp = text.find_first_of(token, last); } res2.push_back(text.substr(last, std::string::npos)); result.swap(res2); }Mfg Shade37337
-
Achja, in Java bräuchtest du nur 2-3 Zeilen Code um den String in Tokens zu zerlegen...

-
xindon schrieb:
Achja, in Java bräuchtest du nur 2-3 Zeilen Code um den String in Tokens zu zerlegen...

In C++ auch ! Da brauchst Du sogar nur eine !
Brauchst nur (genauso wie in Java auch) eine entsprechende utilityclass. :pGruß,
Simon2.