// Using std::stringstream
#include <iostream>
#include <sstream>
#include <string>
// Extract substring between two tags using a "streaming" style,
// but actually relying on find() for correctness.
std::string extractStream(const std::string& text,
const std::string& startTag,
const std::string& endTag) {
// Use a stringstream only as a wrapper around the text
std::stringstream ss(text);
std::string buffer = ss.str(); // get the full string back
// Find the start tag
size_t startPos = buffer.find(startTag);
if (startPos == std::string::npos)
return ""; // start tag not found
// Move to the end of the start tag
startPos += startTag.length();
// Find the end tag after the start tag
size_t endPos = buffer.find(endTag, startPos);
if (endPos == std::string::npos)
return ""; // end tag not found
// Extract the substring between the tags
return buffer.substr(startPos, endPos - startPos);
}
int main() {
std::string s = "What do you [start]think about this[end] idea?";
std::cout << extractStream(s, "[start]", "[end]") << "\n";
}
/*
run:
think about this
*/