CString 字符串转化和分割

时间:2023-03-09 18:37:30
CString 字符串转化和分割
1、格式化字符串

CString s;
s.Format(_T("The num is %d."), i);相当于sprintf()

2、转为 int

转10进制最好用_ttoi(),它在 ANSI 编码系统中被编译成_atoi(),而在 Unicode 编码系统中编译成_wtoi()。用_tcstoul()或者_tcstol()可以把字符串转化成任意进制的(无符号/有符号)长整数。

CString hex = _T("FAB");
CString decimal = _T("4011");
ASSERT(_tcstoul(hex, 0, 16) == _ttoi(decimal));

3、转为 char *

3.1 强制类型转换为 LPCTSTR,不能修改字符串

LPCTSTR p = s; 或者直接 (LPCTSTR)s;

3.2 使用 GetBuffer 方法

不给 GetBuffer 传递参数时它使用默认值 0,意思是:“给我这个字符串的指针,我保证不加长它”。假设你想增加字符串的长度,就必须将你需要的字符空间大小(注意:是字符而不是字节,因为 CString 是以隐含方式感知 Unicode 的)传给它。当调用 ReleaseBuffer 时,字符串的实际长度会被重新计算,然后存入 CString 对象中。
必须强调一点,在 GetBuffer 和 ReleaseBuffer 之间这个范围,一定不能使用你要操作的这个缓冲的 CString 对象的任何方法。因为 ReleaseBuffer 被调用之前,该 CString 对象的完整性得不到保障。

LPTSTR p = s.GetBuffer();
// do something with p
int m = s.GetLength(); // 可能出错!!!
s.ReleaseBuffer();
int n = s.GetLength(); // 保证正确

4、分割字符串

4.1 单字符分割

AfxExtractSubString(CString& rString, LPCTSTR lpszFullString, int iSubString, TCHAR chSep = '\n');

CString csFullString(_T("abcd-efg-hijk-lmn"));
CString csTemp;
AfxExtractSubString(csTemp, (LPCTSTR)csFullString, 0, '-'); // 得到 abcd
AfxExtractSubString(csTemp, (LPCTSTR)csFullString, 1, '-'); // 得到 efg
AfxExtractSubString(csTemp, (LPCTSTR)csFullString, 2, '-'); // 得到 hijk
AfxExtractSubString(csTemp, (LPCTSTR)csFullString, 3, '-'); // 得到 lmn

分隔符可以随便指定:
AfxExtractSubString(csTemp, (LPCTSTR)csFullString, 0, 'f'); // 得到 abcd-e

4.2 字符串分割

利用CString的Find方法,然后再组成数组。

函数:

Split(CString source; CStringArray& dest ; CString division )

参数含义:

CString source--------------需要截取的原字符串,

CStringArray& dest ---------最终结果的数组

CString division -------------用来做分割符的字符串

void Split(CString source, CStringArray& dest, CString division)
{
    dest.RemoveAll();
    int pos = 0;
    int pre_pos = 0;
    while( -1 != pos ){
        pre_pos = pos;
        pos = source.Find(division,(pos+1));
        dest.Add(source.Mid(pre_pos,(pos-pre_pos)));
    }
}