VC字串根據指定字元分割成CStringArray
阿新 • • 發佈:2019-01-28
SplitStr.h #pragma once // CSplitStr class CSplitStr : public CWnd { DECLARE_DYNAMIC(CSplitStr) private: //切分的標誌符號 CString m_sSplitFlag; //連續的切分的標誌符號當成一個標誌處理 BOOL m_bSequenceAsOne; //被切分的文字 CString m_sData; public: CSplitStr(); virtual ~CSplitStr(); //得到切分好的文字串 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;}; protected: DECLARE_MESSAGE_MAP() };
SplitStr.cpp // SplitStr.cpp : 實現檔案 // #include "stdafx.h" #include "SplitStr.h" // CSplitStr IMPLEMENT_DYNAMIC(CSplitStr, CWnd) CSplitStr::CSplitStr() { SetData(""); SetSequenceAsOne(TRUE); SetSplitFlag(","); } CSplitStr::~CSplitStr() { } BEGIN_MESSAGE_MAP(CSplitStr, CWnd) END_MESSAGE_MAP() void CSplitStr::SetData( CString sData ) { m_sData = sData; m_sData.TrimLeft(); m_sData.TrimRight(); } CString CSplitStr::GetData() { return m_sData; } 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 !="") ////連續的分隔符視為單個處理 { array.Add(sTemp); } } sData = sData.Right(sData.GetLength() - pos - 1); } } // CSplitStr 訊息處理程式
呼叫方法:
用法: CSplitStr Split;
CString m_sText = "鵝 鵝 鵝,曲項向天歌,白毛浮綠水,紅掌撥清波";
Split.SetSplitFlag(",");
Split.SetSequenceAsOne(TRUE);
Split.SetData(m_sText);
CStringArray array;
Split.GetSplitStrArray(array);
AfxMessageBox(array[0]);