字句解析・小物集その2

C++タイプのコメント削除

string st;


BYTE byComment = 0;
string::iterator it = st.begin() + 1;
char cChash = 0;
while( it != st.end() ){
	if( byComment == 0 ){
		if( *( it - 1 ) == '/' && *it == '/' ){
			byComment = 1;
			it--;
			it = st.erase( it );
			it = st.erase( it );
		}else if( *( it - 1 ) == '/' && *it == '*' ){
			byComment = 2;
			it--;
			it = st.erase( it );
			it = st.erase( it );
			cChash = 0;
		}else{
			it++;
		}
	}
	if( byComment == 1 ){
		if( *it == '\n' ){
			byComment = 0;
			it++;
		}else{
			it = st.erase( it );
		}
	}
	if( byComment == 2 ){
		if( cChash == '*' && *it == '/' ){
			byComment = 0;
			it = st.erase( it );
			cChash = 0;
		}else{
			cChash = *it;
			it = st.erase( it );
		}
	}
}

ただし、あらかじめ改行が削除されるとうまくいきません。当たり前ですけど。