MFC中CString類的介紹


1、CString類原型

template< typename BaseType, class StringTraits > 
class CStringT :  
public CSimpleStringT< BaseType,   
_CSTRING_IMPL_::_MFCDLLTraitsCheck< BaseType, StringTraits >::c_bIsMFCDLLTraits>

2、常見構造函數的使用

常用構造形式
CString( ) // 無參構造
CString( const CStringT& strSrc ) // 使用CString的引用作為參數構造
CString( const unsigned char* pszSrc ) // 使用const unsigned char *的指針變量構造
CString( char* pszSrc ) // 使用char *的指針變量構造
CString( unsigned char* pszSrc ) // 使用unsigned char *的指針變量構造
CString( wchar_t* pszSrc ) // 使用wchar_t *的指針變量構造(寬字符)
CString( char ch, int nLength = 1 ) // 使用char構造(窄字符)
CString( wchar_t ch, int nLength = 1 ) // 使用wchar_t構造(寬字符)
    
    
測試示例:    
CString s1;                     // Empty string
CString s2(_T("cat"));          // From a C string literal
CString s3 = s2;                // Copy constructor
CString s4(s2 + _T(" ") + s3);  // From a string expression
CString s5(_T('x'));             // s5 = "x"
CString s6(_T('x'), 6);          // s6 = "xxxxxx"
CString s7((LPCSTR)"help"); 	 // char * to CString
CString s8('a', 5);              // s8 = "aaaaa"

3、AppendFormat函數

(1)功能和調用方式類似C語言的sprintf+strcat函數

(2)函數原型

void __cdecl AppendFormat(
   PCXSTR pszFormat,
   [, argument]...
);
void __cdecl AppendFormat(
   UINT nFormatID,
   [, argument]...
);
參數:
pszFormat 需要格式化控制的字符串
nFormatID 包含格式控制字符串的字符串資源標識符(字符串表中的字符串ID號)
argument 可變參數列表

備注:
這個函數在CStringT中格式化並附加一系列字符和值。每個可選參數(如果有)都根據pszFormat中相應的格式規范或nFormatID標識的字符串資源進行轉換和追加。

(3)調用示例

CAtlString str = _T("Some data:\t");
str.AppendFormat(_T("X value = %.2f\n"), 12345.12345);

4、Compare和CompareNoCase函數

(1)作用:比較兩個CString對象是否相等(依賴於strcmp這一類的函數,比較規則依據ASCII碼值大小,並且不受語言環境的影響)

(2)函數原型

// 區分大小寫
int Compare(
   PCXSTR psz
) const;

// 不區分大小寫
int CompareNoCase(
   PCXSTR psz
) const;

參數:
psz 需要比較的字符串,注意:源字符串是調用者

返回值:
	相等返回0
	小於0 則CString對象小於psz字符串
	大於0 則CString對象大於psz字符串

Compare函數備注:
	通用文本函數_tcscmp,它在TCHAR中定義。H,映射到strcmp、wcscmp或_mbscmp,具體取決於在編譯時定義的字符集。每個函數對字符串執行區分大小寫的比較,並且不受語言環境的影響。有關更多信息,請參見strcmp、wcscmp、_mbscmp。如果字符串包含內嵌的空值,為了進行比較,將認為在第一個內嵌的空字符處截斷該字符串。

CompareNoCase函數備注:
	通用文本函數_tcscmp,它在TCHAR中定義。H,映射到strcmp、wcscmp或_mbscmp,具體取決於在編譯時定義的字符集。每個函數對字符串執行不區分大小寫的比較,並且不受語言環境的影響。有關更多信息,請參見strcmp、wcscmp、_mbscmp。如果字符串包含內嵌的空值,為了進行比較,將認為在第一個內嵌的空字符處截斷該字符串。

(3)調用示例

CString str1 = _T("Hello");
CString str2 = _T("hello");
int nRes = str1.Compare(str2);
if (!nRes)
    AfxMessageBox(_T("the strings are identical."));
else if (nRes > 0)
    AfxMessageBox(_T("str1 is greater than str2."));
else
    AfxMessageBox(_T("str1 is less than str2."));

int nRes1 = str1.CompareNoCase(str2);
if (!nRes1)
    AfxMessageBox(_T("the strings are identical."));
else if (nRes1 > 0)
    AfxMessageBox(_T("str1 is greater than str2."));
else
    AfxMessageBox(_T("str1 is less than str2."));

5、Delete函數

(1)作用:從給定索引處的字符開始的字符串中刪除一個或多個字符。

(2)函數原型

int Delete(
   int iIndex,
   int nCount = 1
);
參數:
iIndex 要刪除的CStringT對象中第一個字符的從零開始的索引
nCount 要刪除的字符數量

返回值:
	字符串改變后的長度

備注:
	如果nCount的長度大於字符串的長度,則會把要刪除的第一個字符下標到字符串結尾的字符都刪除。

(3)測試代碼

CString str1 = _T("hello world the word");
str1.Delete(5, 3); // str1 = "hellorld the word"
int nLen = str1.Delete(5, 100); // str1 = "hello"

6、Find函數

(1)作用:在一個大字符串中查找一個字符或者子字符串(以第一個匹配的為准),默認從字符串首地址開始。

調用方式類似(strchr和strstr)。

(2)函數原型

int Find(
   PCXSTR pszSub,
   int iStart=0
) const;

int Find(
   XCHAR ch,
   int iStart=0
) const;
參數:
pszSub 需要查找的子字符串
iStart 查找的開始位置,默認是0,從字符串首元素開始
ch 需要查找的字符

返回值:
	返回值查找到的子串首元素或字符的位置(以大字符串的首地址開始算起);-1表示沒找到。
	
備注:
	這個函數通過重載把strchr和strstr的功能進行了組合。

(3)調用示例

CString str1 = _T("abccdefgh123");
int nIndexch = str1.Find('c'); // nIndexch = 2;
nIndexch = str1.Find('c', 3); // nIndexch = 3;
int nIndexSubStr = str1.Find(_T("fgh")); // nIndexSubStr = 6;
nIndexSubStr = str1.Find(_T("fgdh")); // nIndexSubStr = -1;

7、FindOneOf函數

(1)作用:查找一串字符中的一個字符(以匹配到的第一個字符為准)

(2)函數原型

int FindOneOf(
   PCXSTR pszCharSet
) const;
參數:
pszCharSet 包含需要查找的字符合集的字符串

返回值:
	返回找到的第一個字符的位置(以大字符串的首元素為准),沒找到返回-1

(3)調用示例

CString str1 = _T("abccdefgh123");
int nIndexch = str1.FindOneOf(_T("cdefg")); // nIndexch = 2;
nIndexch = str1.FindOneOf(_T("x1k")); // nIndexch = 9;
nIndexch = str1.FindOneOf(_T("xku")); // nIndexch = -1;

8、Format函數

(1)作用:格式化字符串,使用方法和sprintf一樣

(2)函數原型

void __cdecl Format(
   UINT nFormatID,
   [, argument]...
);
void __cdecl Format(
   PCXSTR pszFormat,
   [, argument]...
);
參數:
nFormatID 包含格式控制字符串的字符串資源標識符。
pszFormat 格式控制字符串
argument 可選參數列表

備注:
	這個函數格式和存儲一串字符和數字到CString對象中,每一個可選參數都會被轉換並輸出到對應的格式格式化字符串pszFormat中或者輸出到指定字符串表ID的對象中。當把調用對象作為參數時,會發生不可預料的結果,導致函數調用失敗。

(3)調用示例

CString str1;
str1.Format(_T("num = %d"), 15); // str1 = "num = 15"
str1.Format(IDS_STRING103, _T("hello")); // IDS_STRING103 = "%s"; str1 = "hello"
TCHAR s[] = _T("hello world");
str1.Format(_T("%s"), (LPCTSTR)s); // str1 = "hello world"

9、GetEnvironmentVariable函數

(1)作用:從調用進程的環境塊中檢索指定變量的值。該值的形式是一個以null結尾的字符串。

(2)函數原型

BOOL GetEnvironmentVariable(
   PCXSTR pszVar
);
參數:
pszVar 需要獲取的環境變量名(以字符串形式)

返回值:
	成功獲取返回非0;失敗返回0

(3)調用示例

CString EnvStr;
EnvStr.GetEnvironmentVariable(_T("TEMP"));
_tprintf_s(_T("Current value of TEMP variable: %s\n"), EnvStr);

10、Insert函數

(1)作用:在指定位置插入一個字符或字符串

(2)函數原型

int Insert(
   int iIndex,
   PCXSTR psz
);
int Insert(
   int iIndex,
   XCHAR ch
);
參數:
	iIndex 插入的起始位置
	psz 待插入的子字符串
	ch 待插入的字符

返回值:
	返回插入后字符串的長度

備注:
	iIndex參數用於指定第一個字符或子串需要插入的位置;如果傳入0,則將會在原字符串的首元素開始插入;如果傳入的下標值超出最大的字符串下標值,則會把待插入的子串或字符進行拼接到原字符串的末尾。

(3)調用示例

CString str(_T("SoccerBest"));
int n = str.Insert(6, _T("is ")); // str = "Socceris Best"
ASSERT(n == str.GetLength()); // n = 13

str.Insert(6, _T(' ')); // str = "Soccer is Best"
str.Insert(55, _T('!')); // str = "Soccer is Best!"
str.Insert(55, _T("CESHI")); // str = "Soccer is Best!CESHI"

11、Left、Right、Mid函數

(1)作用:用於提取子字符串,Left從左邊開始提取n個;Right從右邊開始提取n個;Mid

(2)函數原型

CString Left(
   int nCount
) const;

CString Right(
   int nCount
) const;

CString Mid(
   int iFirst,
   int nCount
) const;

CString Mid(
   int iFirst
) const;
參數:
	nCout 表示需要提取的個數,也就是提取的邊界
	iFirst 表示開始提取的位置(0~字符串長度)

返回值:
	返回一個CString對象
	
備注:
	nCount超出被提取字符串長度,則返回從首位置到末位置的子串;nCount<=0,返回空字符串

(3)調用示例

CString str1 = _T("hello123456");
CString lstr = str1.Left(5); // lstr = "hello"
lstr = str1.Left(20); // lstr = str1
lstr = str1.Left(-1); // lstr = NULL

CString rstr = str1.Right(5); // rstr = "23456"
rstr = str1.Right(20); // rstr = str1
rstr = str1.Right(0); // rstr = NULL

CString midstr = str1.Mid(3, 5); // midstr = "lo123"
midstr = str1.Mid(3, 88); // midstr = "lo123456"
midstr = str1.Mid(3, -1); // midstr = ""

12、MakeLower、MakeUpper、MakeReverse函數

(1)作用:轉換字母的大小寫及翻轉字符串

(2)函數原型

CString& MakeLower(); // 全部字母轉換為小寫
CString& MakeUpper(); // 全部字母轉換為大寫
CString& MakeReverse(); // 翻轉字符串

(3)調用示例

CString s(_T("abc"));
ASSERT(s.MakeUpper() == _T("ABC")); // TRUE
ASSERT(s.MakeLower() == _T("abc")); // TRUE
ASSERT(s.MakeReverse() == _T("cba")); // TRUE

13、Remove函數

(1)作用:移除字符串中指定的字符

(2)函數原型

int Remove(
   XCHAR chRemove
);
參數:
	chRemove 需要移除的字符

返回值:
	返回被移除的字符個數;0則說明原字符串沒有被改動

備注:
	字符之間的比較方式是采用區分大小寫的形式

(3)調用示例

CString str1 = _T("This is a test.");
ASSERT(str1.Remove(_T('t')) == 2); // str1 = "This is a es."

14、Replace函數

(1)作用:替換目標字符串中的某種字符或字符串

(2)函數原型

int Replace(
   PCXSTR pszOld,
   PCXSTR pszNew
);
int Replace(
   XCHAR chOld,
   XCHAR chNew
);
參數:
pszOld 指向一個以空字符結束的字符串,用於被新字符串替換
pszNew 指向一個以空字符結束的字符串,用於替換舊字符串
chOld 需要被替換的字符
chNew 新替換進去的字符

返回值:
	返回被替換的個數,如果返回0,表示沒有替換。

備注:
	Replace可以更改字符串長度,因為pszNew和pszOld不必具有相同的長度,並且可以將舊子字符串的多個副本更改為新子字符串。該函數執行區分大小寫的匹配。

(3)調用示例

CString strBang(_T("Everybody likes epee fencing"));
int n = strBang.Replace(_T("epee"), _T("foil"));
ASSERT(n == 1); // TRUE

15、SpanExcluding和SpanIncluding函數

(1)作用:從左邊的第一個字符開始查找與給定串相等的字符,如果沒有則返回空的串,反之,繼續查找,到結束

SpanExcluding則相反,查找不匹配的;

(2)函數原型

CString SpanExcluding(
   PCXSTR pszCharSet
) const;

CStringT SpanIncluding(
   PCXSTR pszCharSet
) const;
參數:
	pszCharSet 需要提取或排除字符的組合

返回值:
	返回一個CString對象

備注:
SpanIncluding函數:
如果被提取字符串中的第一個字符不在pszCharSet中,則返回空字符串;否則返回一個連續的字符串。
	
SpanExcluding函數:
返回遇到pszCharSet參數中第一個字符前面的所有字符。如果沒匹配到字符合集中的字符,則返回整個字符串。


常見用途:判斷接收到的字符串是不是全為數字
BOOL IsDigital(CString str)
{
	return str==str.SpanIncluding("0123456789");
}

(3)調用示例

/* 在str中提取與strDigtal想等的串,從第一個'5’開始查找,....,
直到str中的一個字符在strDigtal找不到...,例子中,'9'條件不符,直接返回"51" 
*/
CString str;
CString strDigital("0123456");
str = "51920";
CString strVal = str.SpanIncluding(strDigital);
MessageBox(strVal); // strVal = "51"

// 查找到'6'的時候不匹配,返回"98"
str1 = "9867578";
CString strVal1 = str.SpanExcluding(strDigital);
MessageBox(strVal1); // strVal1 = "98"

16、Tokenize函數

(1)作用:分割字符串,使用多個分隔符(分隔符的順序無關緊要)。

(2)函數原型

CString Tokenize(
   PCXSTR pszTokens,
   int& iStart
) const;
參數:
	pszTokens 分割符合集字符串
	iStart 分割的起始位置

返回值:
	CString對象

備注:
	Tokenize函數查找目標字符串中的下一個分隔符。psztoken中的字符集指定要找到的可能分隔符。在每次調用Tokenize函數時,函數從iStart開始,跳過前導分隔符,並返回一個包含當前標記的CStringT對象,該標記是下一個分隔符字符之前的字符串。iStart的值被更新為結束分隔符字符之后的位置,如果到達字符串的結尾,則更新為-1。通過一系列Tokenize調用,可以從目標字符串的其余部分中取出更多的標記,使用iStart跟蹤字符串中下一個標記的讀取位置。當沒有更多的標記時,函數將返回一個空字符串,iStart將被設置為-1。

(3)調用示例

CAtlString str(_T("%First Second#Third"));
CAtlString resToken;
int curPos = 0;

resToken = str.Tokenize(_T("% #"), curPos);
while (resToken != _T(""))
{
    AfxMessageBox(resToken);
    resToken = str.Tokenize(_T("% #"), curPos);
}
/*
輸出結果為:
第一次:First
第二次:Second
第三次:Third
*/

17、Trim函數

(1)作用:刪除字符串兩邊緣中指定的字符

(2)函數原型

CStringT& Trim(
   XCHAR chTarget 
);
CStringT& Trim(
   PCXSTR pszTargets 
);
CStringT& Trim( );
參數:
chTarget 需要刪除的目標字符

pszTargets 指向包含要裁剪的目標字符的字符串的指針。pszTarget中出現的所有前導字符和尾隨字符都將從CStringT對象中刪除。

(3)調用示例

CAtlString str;
str = _T("******Soccer is best!?!?!?!?!");

_tprintf_s(_T("Before: \"%s\"\n"), (LPCTSTR)str);
_tprintf_s(_T("After : \"%s\"\n"), (LPCTSTR)str.Trim(_T("?!*")));

// Output: 
// -------------------------- 
// Before: ******Soccer is best!?!?!?!?! 
// After: Soccer is best

18、TrimLeft和TrimRight

(1)作用:移除前導元素(TrimLeft)、移除

(2)函數原型

CStringT& TrimLeft(
   XCHAR chTarget 
);
CStringT& TrimLeft(
   PCXSTR pszTargets 
);
CStringT& TrimLeft( );

CStringT& TrimRight(
   XCHAR chTarget 
);
CStringT& TrimRight(
   PCXSTR pszTargets 
);
CStringT& TrimRight( );
參數:
chTarget 需要刪除的目標字符
pszTargets 指向包含要裁剪的目標字符的字符串的指針。pszTarget中出現的所有前導字符和尾隨字符都將從CStringT對象中刪除。

返回值:
	CStringT對象

備注:
刪除下列任一項的所有前導和尾隨:
		由chTarget指定的字符。
		在pszTargets指定的字符串中找到的所有字符。
		空格。
		在TrimRight中空白符可以是換行符、空格或制表符。

(3)調用示例

/* TrimRight測試代碼 */
	CString str = _T("    ****This a test code~~~@@@+++@@    @@");
	CString str2 = str.Trim(_T('@'));
	CString str1 = str.TrimRight(); // 移除空格

/* TrimLeft測試代碼 */
	CString str = _T("    ****This a test code~~~@@@+++@@    @@");
	CString str1 = str.TrimLeft(); // 移除空格
	CString str2 = str.Trim(_T('*'));


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM