当前位置:网站首页>CString string splitting function

CString string splitting function

2022-06-10 09:07:00 Pepsi__

This is a passage written by the great God to realize CString String segmentation function code

#include <vector>  // Reference header file 
using std::vector;

int SplitCString(const CString& str,const char * separator,int sep_number, vector<CString> &strArray)
{
	strArray.clear();
	int index  = -1;
	const int MAX_COUNT = 1000000; // Maximum segmentation length 
	int smallIndex = MAX_COUNT;
	CString szLeft;
	CString szRight = str;	

	for (int i = 0; i< sep_number; i++)
	{
		index = szRight.Find(separator[i]);
		if (index >= 0 && index < smallIndex)
		{
			smallIndex = index; // Traverse to get the minimum of all separators Index
		}

		if (i == sep_number-1 && smallIndex != MAX_COUNT) // After traversing all the delimiters 
		{	
			szLeft = szRight.Left(smallIndex);
			szLeft.Trim(); // Remove the space 
			if (!szLeft.IsEmpty()) strArray.push_back(szLeft);

			szRight = szRight.Right(szRight.GetLength()-smallIndex-1);
			szRight .Trim();
			if (szRight.GetLength()>0)
			{
				i = -1;
				smallIndex = MAX_COUNT;
			}
			else break;
		}
		else if (i == sep_number-1)
		{
			szRight.Trim();
			if(!szRight.IsEmpty()) strArray.push_back(szRight);
		}
	}	

	return strArray.size();
}

Although I don't understand how it is realized , But the way to use it is

char separator[2] = {':', '.'};
CString strTime = "00:10:22.43";
vector<CString> arrayText;
SplitCString(strTime ,separator,sizeof(separator),arrayText);

arrayText The container will contain the four pieces that have been divided CString:“00”、“10”、“22”、“43”. The characters used as segmentation marks are stored in separator In an array . The string used for segmentation is strTime.

Reference article :
CString String segmentation ( Multiple characters as separator )

原网站

版权声明
本文为[Pepsi__]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206100832322909.html