1. 程式人生 > >CString 擷取部分字串的幾種方法

CString 擷取部分字串的幾種方法

m_csFileName = csStr.Right(csStr.GetLength()-csStr.ReverseFind('\\')-1);
檔案xxxx.dll去掉後面的.dll
方法1、
char str[] = "xxxx.dll"
char*p;
p=strrchr(str, '.');
*p = 0;

方法2、
CString str="xxxx.dll";
int n = str.ReverseFind('.')
str = str.Left(str.GetLength()-n-1);

例程2:(csdn)

取得一個字串中第一個 '?'號之前的字元
方法1
CString m_char,m_disp;
m_disp="jadfueiuajdf?";
m_char="?";
if (!m_char.IsEmpty())
   {
       int index = m_disp.Find(m_char);
       m_disp = m_disp.Right(m_disp.GetLength()-index-1);
   }
返回m_disp就行

方法2
CString temp=the.m_bb;
CString reslut=temp.Left(temp.Find("?")-1);

例程3:(csdn)
一個CString類物件m_StrReceiveModem={ATS0=2  
                        OK
                        $03#}
如何擷取從$開始的字串
方法1

       CString m_StrReceiveModem;
       int nPos = m_StrReceiveModem.Find('$');
       if(nPos >= 0)
       {
           CString sSubStr = m_StrReceiveModem.Mid(nPos);//包含$,不想包含時nPos+1
       }

方法2
CString m_StrReceiveModem;
       int nPos = m_StrReceiveModem.Find('$');
       if(nPos >= 0)
       {
           CString sSubStr = m_StrReceiveModem.Right(StrReceiveModem.GetLength()-nPos); 

       }

以及Mid(int nFirst,int nSize)

定義CString 要找到的一個串擷取這個串怎麼辦???
CString = "abcde base64 baaaaa" 
要把base64後面的字串保留.怎麼處理???? 
現在你給出的字串已經知道了長度,而且也知道分隔位置在哪兒,直接可以用CString::Right()函式獲取後半截,如下:
CString str="abcde base64 baaaaa";
str=str.Right(6);//等式右邊得到str的後6個字元組成的字串然後賦值給str
如果先前不知道分割點的確切位置的話,可以用如下函式查詢:
CString::Find() //1
CString::FindOneOf() //2
函式1有如下幾個原型:
int Find( TCHAR ch ) const;
int Find( LPCTSTR lpszSub ) const;
int Find( TCHAR ch, int nStart ) const;
int Find( LPCTSTR lpszSub, int nStart ) const;
函式2的原型為:
int FindOneOf( LPCTSTR lpszCharSet ) const;
找到分隔點位置後就可以截取了。
與CString::Right(int n)相對的還有CString::Left(int n),它是用來擷取字串前面n個字元的 

CString str="abcde base64 baaaaa";
CString findstr="base64";
CString mystr;
int k=str.Find(findstr)+findstr.GetLength();
mystr= str.Right(str.GetLength()- k); 
CString cs;
返回左邊的值,cs.left(int x) x為幾位;
返回右邊的值,cs.right(int x) x為幾位;
cs.GetLength();;
我覺得有上面的3個函式,你會使用的話,CString 裡面的任意 字元段 都截出來了 

AfxMessageBox(mystr);

字串:D:\cr14\PE\MFC_PE\Debug\MFC_PE.exe

擷取目標:MFC_PE.exe

方法:m_csFileName = csStr.Right(csStr.GetLength()-csStr.ReverseFind('\\')-1);