CString截取字串方法

來源:互聯網
上載者:User

C中CString類型好像沒有像string.SubString(parame)這樣類似的函數來從字串中直接分離子串,但是我們可以藉助CString的幾個函數來實現。

在CString中有Find(),Delete(),Left(),Right(),Mid()就可以實現分離子串的目的了。

intFind( TCHAR ch ) const;

找到給定的字元返回它在字串中對應的索引號;沒有找到就返回-1。

intDelete( int nIndex, int nCount = 1);

傳回值是被刪除前的字串的長度,nIndex是第一個被刪除的字元索引,nCount是一次刪除幾個字元。當nCount過大,沒有足夠的字元刪除時,此函數不執行。

CStringLeft( int nCount ) const;

返回的字串是前nCount個字元。

CStringMid( int nFirst ) const;

CStringMid( int nFirst, int nCount ) const;

nCount代表要提取的字元數, nFirst代表要提取的開始索引位置

CStringRight( int nCount ) const;

返回的字串是後nCount個字元。

簡例:

CStringstr(”MyNameIsRenZheng”);

CStringstr1, str2, str3;

intx,y;

x=str.Find(_T("N"));   //2

y=str.Delete(0,5);  // 16

str1 =str.Left(3);   // MyN

str2 =str.Mid(11, 4);  //Zhen。注意,第二個參數是代表子串的長度

str3 =str.Right(3);  // eng

假使有CString str=_T("My name is Ren Zheng");

按空格提取子串可以採用如下方法:

CStringstr=_T("My name is Ren Zheng");

CArray<CString,CString>strArray;  //定義一個CString類型的動態數組,用來存取CString類型對象。

while(str.Find(_T(" "))+1)//當找不到空格時返回-1,所以這裡我用它傳回值加1來迴圈

{

strArray.Add(str.Left(str.Find(_T(“”))));//找到空格的索引,截取空格左邊的字串,並將它添加到strArray動態數組中。

str.Delete(0,str1. GetLength_r()+1);//返回刪除空格和其左邊的字串的得到的新字串。

}

strArray.Add(str);//最後加上經過最終刪除後剩下的字串;

這樣按空格分離出的子串就都儲存在動態CString類型的數組對象strArray中去了,現在就可以用strArray. Get_r(i)來得到每個子串;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.