In the process of doing, often need to text according to the fixed flag to split, the CString class provides some basic string operations, this article is to use the basic functions of CString class to achieve the free text string splitting, the following figure:
The design of text string-splitting classification
The split of text is encapsulated into a separate class for code reuse, and the class is designed as follows:SplitStr.h
class CSplitStr
{
private:
//切分的标志符号
CString m_sSplitFlag;
//连续的切分的标志符号当成一个标志处理
BOOL m_bSequenceAsOne;
//被切分的文本
CString m_sData;
public:
//得到切分好的文本串
void GetSplitStrArray(CStringArray &array);
//得到被切分的文本
CString GetData();
//设置被切分的文本
void SetData(CString sData);
//得到切分参数
BOOL GetSequenceAsOne() {return m_bSequenceAsOne;};
//设置切分参数
void SetSequenceAsOne(BOOL bSequenceAsOne) {m_bSequenceAsOne = bSequenceAsOne;};
//得到切分标志
CString GetSplitFlag() {return m_sSplitFlag;};
//设置切分标志
void SetSplitFlag(CString sSplitFlag) {m_sSplitFlag = sSplitFlag;};
CSplitStr();
virtual ~CSplitStr();
};
Implementation file: SplitStr.cpp
Constructors
Csplitstr::csplitstr ()
{
SetData ("");
Setsequenceasone (TRUE);
Setsplitflag (",");
}
Csplitstr::~csplitstr ()
{
}
Set text functions
void Csplitstr::setdata (CString sData)
{
M_sdata = SData;
M_sdata.trimleft ();
M_sdata.trimright ();
}
CString Csplitstr::getdata ()
{
return m_sdata;
}
Shard operation function (very simple and practical)
void Csplitstr::getsplitstrarray (CStringArray &array)
{
CString sData = GetData ();
CString Ssplitflag = Getsplitflag ();
if (Sdata.right (1)!= ssplitflag) SData +=ssplitflag;
CString stemp;
int POS =-1;
while ((Pos=sdata.find (ssplitflag,0))!=-1)
{
Stemp = Sdata.left (POS);
if (! Getsequenceasone ())
{
Array. ADD (stemp);
}
Else
{
if (!stemp.isempty () && stemp!= "")////consecutive delimiters as a single processing
{
Array. ADD (stemp);
}
}
SData = Sdata.right (Sdata.getlength ()-pos-1);
}
}
Second, the use of text-string split classification
#include <afxtempl.h>
#include "SplitStr.h"
CSplitStr Split;
Cstring m_sText = “你好,,欢迎使用文本切分类,作者:江上飞鸟,qq: 36201365”;
Split.SetSplitFlag(",");
Split.SetSequenceAsOne(TRUE);
Split.SetData(m_sText);
CStringArray array;
Split.GetSplitStrArray(array);
The best output results are:array[0] = “你好”;
array[1] = “欢迎使用文本切分类”;
array[2] = “作者:江上飞鸟”;
array[3] = “qq: 36201365”;
This article supporting source code