Splitting CString to array in MFC



The following function converts string to array in MFC & ATL. By default it trims each string in the array and also ignores empty strings. It uses CString MFC class and CAtlArray ATL class.

//converts semicolon separated string to array of strings
void StringToArray(CString & strValue, CAtlArray<CString> & arrValue, TCHAR szSeparator, BOOL bTrim/*=TRUE*/, BOOL bIgnoreEmptyString/*=TRUE*/)
{
	int idx;
	CString strTemp,strRest;
 
	strRest = strValue;
 
	if (strRest.IsEmpty()) {
		arrValue.RemoveAll();
		return;
	}
	do
	{
		idx = strRest.Find(szSeparator);
 
		if (idx != -1)
		{
			//take the left part
			strTemp = strRest.Left(idx);
 
			if (bTrim)
			{
				strTemp.Trim();
			}
 
			if ( (bIgnoreEmptyString) && strTemp.IsEmpty() )
			{
				//ignore
			}else
			{
				arrValue.Add(strTemp);
			}
 
			strRest = strRest.Right(strRest.GetLength()-idx-1);
 
		}else
		{
			if (bTrim)
			{
				strRest.Trim();
			}
 
			if (!strRest.IsEmpty())
			{
				//this is the last element, so lets add it
				arrValue.Add(strRest);
			}
		}
 
	}while(idx != -1);
 
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">