I am parsing a string in C++ using the following:
using namespace std;
string parsed,input="text to be parsed";
stringstream input_stringstream(input);
if (getline(input_stringstream,parsed,' '))
{
// do some processing.
}
Parsing with a single char delimiter is fine. But what if I want to use a string as delimiter.
Example: I want to split:
scott>=tiger
with >=
as delimiter so that I can get scott and tiger.
Best Answer
You can use the
std::string::find()
function to find the position of your string delimiter, then usestd::string::substr()
to get a token.Example:
The
find(const string& str, size_t pos = 0)
function returns the position of the first occurrence ofstr
in the string, ornpos
if the string is not found.The
substr(size_t pos = 0, size_t n = npos)
function returns a substring of the object, starting at positionpos
and of lengthnpos
.If you have multiple delimiters, after you have extracted one token, you can remove it (delimiter included) to proceed with subsequent extractions (if you want to preserve the original string, just use
s = s.substr(pos + delimiter.length());
):This way you can easily loop to get each token.
Complete Example
Output: