Convert array/list to string using a separator in C++ (MFC)



Following is the code to convert array to string using a specific separator. Language used is C++ using MFC (Microsoft Foundation Classes).

This function can trim each term in the array and also ignore blank (empty) string.

You can easily modify it for list or any other similar collection class.

void ArrayToString(CAtlArray<CString> & arrValue, CString & strValue, CString strSeparator
					, BOOL bTrim/*=TRUE*/, BOOL bIgnoreEmptyString/*=TRUE*/)
{
	int i;
	strValue.Empty();
	CString strItem;
 
	//append all strings with ; as separator
	for(i=0;i<int(arrValue.GetCount());i++)
	{
		strItem = arrValue[i];
 
		if (bTrim)
		{
			strItem.Trim();
		}
 
		if (bIgnoreEmptyString)
		{
			if (strItem.IsEmpty())
			{
				continue;
			}
		}
 
		strValue += strItem;
 
 
		if (i < (int(arrValue.GetCount())-1))
		{
			strValue += strSeparator;
		}
 
	}
 
}


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);
 
}