include/StringUtils.hxx
// strips everything right of comment
// does not strip whitespace before comment
strips everything right of comment
does not strip whitespace before comment
strips everything right of comment does not strip whitespace before comment
inline std::string stripComment(const std::string &s, const std::string &commentDelimiter = "#")
{
	std::vector<std::string::size_type> quoteBegins;
	std::vector<std::string::size_type> quoteEnds;
	for (std::string::size_type i = 0; i < s.size(); ++i)
	{
		char c = s[i];
		if (c == '\"' && (i == 0 || s[i-1] != '\\')) 
		{
			if (quoteBegins.size() > quoteEnds.size())
			{
				quoteEnds.push_back(i);
			}
			else
			{
				quoteBegins.push_back(i);
			}
		}
	}
	int nStrings = std::min(int(quoteBegins.size()), int(quoteEnds.size()));
	std::string::size_type searchOffset = 0;
	while (searchOffset < s.size())
	{
		std::string::size_type p = s.find(commentDelimiter, searchOffset);
		if (p == std::string::npos) 
			return s;
		bool isInString = false;
		for (int k = 0; k < nStrings; ++k)
		{
			if (p >= quoteBegins[k] && p < quoteEnds[k])
			{
				isInString = true;
				break;
			}
		}
		if (!isInString) 
			return s.substr(0, p - 0);
		else 
			searchOffset = p+1;
	}
	return s;
}
inline std :: string stripComment ( const std :: string & s , const std :: string & commentDelimiter = " " ) { std :: vector < std :: string :: size_type > quoteBegins ; std :: vector < std :: string :: size_type > quoteEnds ; for ( std :: string :: size_type i = 0 ; i < s . size ( ) ; ++ i ) { char c = s [ i ] ; if ( c == ' \" ' && ( i == 0 || s [ i - 1 ] != ' \\ ' ) ) { if ( quoteBegins . size ( ) > quoteEnds . size ( ) ) { quoteEnds . push_back ( i ) ; } else { quoteBegins . push_back ( i ) ; } } } int nStrings = std :: min ( int ( quoteBegins . size ( ) ) , int ( quoteEnds . size ( ) ) ) ; std :: string :: size_type searchOffset = 0 ; while ( searchOffset < s . size ( ) ) { std :: string :: size_type p = s . find ( commentDelimiter , searchOffset ) ; if ( p == std :: string :: npos ) return s ; bool isInString = false ; for ( int k = 0 ; k < nStrings ; ++ k ) { if ( p >= quoteBegins [ k ] && p < quoteEnds [ k ] ) { isInString = true ; break ; } } if ( ! isInString ) return s . substr ( 0 , p - 0 ) ; else searchOffset = p + 1 ; } return s ; }
strips everything right of comment
does not strip whitespace before comment
strips everything right of comment does not strip whitespace before comment
// ad-hoc method to avoid considering delimiter within double quoted string as comment: // XXX: probably doesn't work in all cases, and not terribly efficient // ", but not \" // check for comment delimiter: // no comment delimiter found, return whole string // check if inside double quoted string: // comment delimiter found, but not in inside string; return string upto comment // comment delimiter found, but inside string; try again with new search offset