Splitting A String

Started by
6 comments, last by Antheus 16 years, 3 months ago
Hello Language - c++ allways forget that im trying to take a string and split it at a "=" So for example if i have a string containing something1=something2 I need to get the something2 into its own string How do i do that? [Edited by - randomperson on December 20, 2007 5:38:50 AM]
Advertisement
In what language?
Assuming C++:
std::string str = "something1=something2";size_t nPos = str.find('=');if(nPos == std::string::npos)   return; // Not foundstd::string strA = str.substr(0, nPos);std::string strB = str.substr(nPos+1);
thanks that works great :D
You should probably split it using iterator collections instead. Look into how boost does it. Doesn't really matter here but if you really want to avoid a lot of repetitive grunt work which has already been solved I would really consider looking at boost. This is probably for configuration files or arguments? If so boost has a library for that already ready for you to use.
Thanks but i prefer to do things myself
Quote:Original post by ortsa
Thanks but i prefer to do things myself
The further you get into programming and software development, the less effective this particular ethos (which we hear proclaimed quite frequently here on GDNet) is likely to be.

In short, creating a non-trivial application in C++ is a sizable task (especially for one person), so much so that whether or not you avail yourself of existing solutions where possible can end up being a determining factor in whether your project succeeds or fails. If you're writing short exercises or other trivial programs, doing everything yourself is probably not impractical, and can be a good learning experience. Otherwise though, I'd suggest looking into some of the tools suggested above.

Personally, in C++ I generally use boost::split() (from the string algorithms library) or boost::tokenizer whenever I need to do simple text parsing.
Given that this is most likely a configuration file, boost::program_options might be optimal choice (it has a kitchen sink and cleans windows too).

For XML, there's also suitable parsers.

String parsing tends to be deceivingly trivial, until weird things start to happen, or syntax becomes too complex.

This topic is closed to new replies.

Advertisement