MFC下編寫的Split函數

來源:互聯網
上載者:User
代碼

四個參數說明如下:
a:要分割的字串
b:存放的數組,要定義到足夠能放下所有分割結果。
c:分割後實際產生的數組元素最大下標,如果沒有元素產生,則函數調用後為-1。注意,c在函數調用後值要發生變化,這是一個地址引用參數。
d:分隔字元,長度不限,並不限定為一個字元
void Split(CString a, CString *b, int &c, CString d)
{
int d_len=d.GetLength();
int j=0;
int n=0;
int m_pos;
while(1)
{
   m_pos= a.Find(d,j);
   if(m_pos==-1 && j==0)
        {
    c=-1;
    break;
   }
 
   if(m_pos==-1 && j!=0)
   {
    b[n]=a.Mid(j,a.GetLength()-j);
    c=n;
    break;
   }
 
   if(j==0)
   {
    b[n]=a.Mid(0,m_pos);
    j=m_pos+d_len;
   }
   else
   {
    b[n]=a.Mid(j,m_pos-j);
    j=m_pos+d_len;
   }
   n++;
}
}
下面舉例說明調用方法:
CString b[20];
CString a="hello0|!nihao|!how are you|!123456|!111";
int c=0;
CString d="!";
CString t;
 
Split(a,b,c,d);
if (c!=-1)
{
for (int i=0;i<=c;i++)
{
AfxMessageBox(b[i]);
}
}
else
{
AfxMessageBox("找不到此項");
}
 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.