Here you go, a complete function that can retrieve a sub-string from a std::string. A good documentation on this function is also included.
#pragma region INFO
/*
* @ FUNCTION: GetSubStrBetween
*
* @ PARAMETER(s):
* [1st] std::string &in_Str = This paramter takes in a std::string, which
* is the string that contains the unknown sub-string.
*
* [2nd] std::string in_A = This parameter takes in a std::string, which
* will be the beginning point of the unknown sub-string.
*
* [3rd] std::string in_B = This parameter takes in a std::string, which
* happens to be the ending point of the unknown sub-string.
*
* [4th] std::string in_out_SubStr = This parameter takes in a std::string,
* which will contain the unknown sub-string.
*
* [5th] bool in_opt_Append = This optional* parameter takes in either a true
* or false value. If in_opt_Append = true, in_out_SubStr (see 4th
* param.) will append the unknown sub-str. Else, in_out_SubStr will be
* equal to the unknown sub-str. Note: The default value is false.
*
* @ RETURN VALUE(s):
* false = This function returns a false value because...
* - The length of in_Str/in_A/in_B is equal to 0.
* - The length of in_A/in_B is greater than or equal to the length
* of in_Str.
* - The length of in_Str is smaller than length of in_A + the length
* of in_B.
* - Unable to find in_A/in_B.
* true = Successfully found and return the unknown sub-str to in_out_SubStr.
*/
#pragma endregion INFO
bool GetSubStrBetween( std::string &in_Str,
std::string in_A,
std::string in_B,
std::string &in_out_SubStr,
bool in_opt_Append = false )
{
//# Check for possible errors.
if( in_A.length() == 0 ||
in_B.length() == 0 ||
in_Str.length() == 0 ||
in_Str.length() <= in_A.length() ||
in_Str.length() <= in_B.length() ||
in_Str.length() < in_A.length() + in_B.length() )
{ return false; }
//# Try to find the positions of in_A and in_B within in_Str.
const int A_Pos = in_Str.find( in_A );
const int B_Pos = in_Str.find( in_B );
//# Check if in_A and in_B does exist within in_Str.
if( A_Pos < 0 || B_Pos < 0 )
{ return false; }
//# Retrieve the unknown-substr and either append it to in_out_SubStr
// or make in_out_SubStr equal to the unknown sub-string.
( in_opt_Append == true ) ?
( in_out_SubStr = in_Str.substr( A_Pos + 1, B_Pos - 1 - A_Pos ) ) :
( in_out_SubStr += in_Str.substr( A_Pos + 1, B_Pos - 1 - A_Pos ) );
//# Success!
return true;
};
Do not forget to include string.
Here is a usage example based on the question above:
std::string Str = "asdfgsdfg:ijtij ijdfgh ija::saf 1999 bp";
std::string SubStr = "";
if( GetSubStrBetween( Str, ":", "bp", SubStr ) ) {
std::cout << std::endl << GetSubStrBetween << std::endl;
} else { std::cout << "\nGetSubStrBetween(...) has failed!\n"; }