CString Class

CString

CString does not have a base class.

A CString object consists of a variable-length sequence of characters.CString provides functions and operators using a syntax similar to that of Basic. Concatenation and comparison operators, together with simplified memory management, makeCString objects easier to use than ordinary character arrays.

CString is based on the TCHAR data type. If the symbol_UNICODE is defined for your program, TCHAR is defined as typewchar_t, a 16-bit character type; otherwise, it is defined as char, the normal 8-bit character type. Under Unicode, then, CString objects are composed of 16-bit characters. Without Unicode, they are composed of 8-bitchar type.

When not using _UNICODE, CString is enabled for multibyte character sets (MBCS, also known as double-byte character sets, DBCS). Note that for MBCS strings,CString still counts, returns, and manipulates strings based on 8-bit characters, and your application must interpret MBCS lead and trail bytes itself.

CString objects also have the following characteristics:

  • CString objects can grow as a result of concatenation operations.

  • CString objects follow “value semantics.” Think of a CString object as an actual string, not as a pointer to a string.

  • You can freely substitute CString objects for const char* andLPCTSTR function arguments.

  • A conversion operator gives direct access to the string’s characters as a read-only array of characters (a C-style string).

Tip   Where possible, allocateCString objects on the frame rather than on the heap. This saves memory and simplifies parameter passing.

CString assists you in conserving memory space by allowing two strings sharing the same value also to share the same buffer space.  However, if you attempt to change the contents of the buffer directly (not using MFC), you can alter both strings unintentionally. CString provides two member functions,CString::LockBuffer and CString::UnlockBuffer, to help you protect your data.  When you call LockBuffer, you create a copy of a string, then set the reference count to -1, which "locks" the buffer. While the buffer is locked, no other string can reference the data in that string, and the locked string will not reference another string. By locking the string in the buffer, you ensure that the string’s exclusive hold on the data will remain intact. When you have finished with the data, callUnlockBuffer to reset the reference count to 1.

For more information, see theStrings in MFC andStrings: Unicode and Multibyte Character Set (MBCS) Support articles inVisual C++ Programmer’s Guide andString Manipulation Routines in theRun-Time Library Reference.

#include <afx.h>


CString Class Members

Construction
The String as an Array
Assignment/Concatenation
Comparison
Extraction
Other Conversions
Searching
Archive/Dump
Buffer Access
Windows-Specific

Construction

CStringConstructs CString objects in various ways.

The String as an Array

GetLengthReturns the number of characters in a CString object. For multibyte characters, counts each 8-bit character; that is, a lead and trail byte in one multibyte character are counted as two characters.
int GetLength( ) const;
返回字符串的长度,不包含结尾的空字符。
    csStr="ABCDef中文123456";
    printf("%d",csStr.GetLength());       //16
IsEmptyTests whether a CString object contains no characters.
BOOL IsEmpty( ) const;
测试对象是否为空,为空时返回零,不为空时返回非零
    csStr="abc";
    cout<<csStr.IsEmpty();         //0;
    csStr.Empty();
    cout<<csStr.IsEmpty();         //1;
EmptyForces a string to have 0 length.
void Empty( );
清空
    csStr="abcdef";
    csStr.Empty();
    printf("%d",csStr.GetLength());    //0
GetAtReturns the character at a given position.
TCHAR GetAt( int nIndex ) const;
返回下标为nIndex的字符,与字符串的[]用法相同
    csStr="abcdef";
    cout<<csStr.GetAt(2);             //c
当nIndex为负数或超出对象末尾时,会发生无法预料的结果。
operator []Returns the character at a given position — operator substitution forGetAt.
TCHAR operator []( int nIndex ) const;
返回在指定位置的字符
    CString s( "abc" );
    ASSERT( s[1] == 'b' );
SetAtSets a character at a given position.
void SetAt( int nIndex, TCHAR ch );
给下标为nIndex的字符重新赋值
    csStr="abcdef";
    csStr.SetAt(2,'x');
    cout<<csStr;                      //abxdef
当nIndex为负数或超出对象末尾时,会发生无法预料的结果。
operator LPCTSTR Directly accesses characters stored in a CString object as a C-style string.
operator LPCTSTR ( ) const;
// If the prototype of a function is known to the compiler,
// the LPCTSTR cast operator may be invoked implicitly
    CString strSports(_T("Hockey is Best!"));
    TCHAR sz[1024];
    lstrcpy(sz, strSports);
// If the prototype isn't known, or is a va_arg prototype,
// you must invoke the cast operator explicitly. For example,
// the va_arg part of a call to sprintf() needs the cast:
    sprintf(sz, "I think that %s!\n", (LPCTSTR) strSports);
// while the format parameter is known to be an LPCTSTR and
// therefore doesn't need the cast:
    sprintf(sz, strSports);
// Note that some situations are ambiguous. This line will
// put the address of the strSports object to stdout:
    cout << strSports;
// while this line will put the content of the string out:
    cout << (LPCTSTR) strSports;

Assignment/Concatenation

operator =Assigns a new value to a CString object.
const CString& operator =( const CString& stringSrc );
throw( CMemoryException );
const CString& operator =( TCHAR ch );
throw( CMemoryException );
const CString& operator =( const unsigned char* psz );
throw( CMemoryException );
const CString& operator =( LPCWSTR lpsz );
throw( CMemoryException );
const CString& operator =( LPCSTR lpsz );
throw( CMemoryException );
    CString s1, s2;        // Empty CString objects
    s1 = "cat";            // s1 = "cat"
    s2 = s1;               // s1 and s2 each = "cat"
    s1 = "the " + s1;      // Or expressions
    s1 = 'x';              // Or just individual characters
operator +Concatenates two strings and returns a new string.
friend CString operator +( const CString& string1, const CString& string2 );
throw( CMemoryException );
friend CString operator +( const CString& string, TCHAR ch );
throw( CMemoryException );
friend CString operator +( TCHAR ch, const CString& string );
throw( CMemoryException );
friend CString operator +( const CString& string, LPCTSTR lpsz );
throw( CMemoryException );
friend CString operator +( LPCTSTR lpsz, const CString& string );
throw( CMemoryException );
    CString str(_T("abc"));
    str = _T("de") + str + _T("kp"); //str == deabckp
operator +=Concatenates a new string to the end of an existing string.
const CString& operator +=( const CString& string );
throw( CMemoryException );
const CString& operator +=( TCHAR ch );
throw( CMemoryException );
const CString& operator +=( LPCTSTR lpsz );
throw( CMemoryException );
    CString str(_T("abc"));
    str = _T("de") + str + _T("kp"); //str == deabckp
    str += _T("123"); //str == deabckp123
    TCHAR szBuf[] = _T("789");
    str += szBuf; //str == deabckp123789

Comparison

operator == <, etc.Comparison operators (case sensitive).
BOOL operator ==( const CString& s1, const CString& s2 );
BOOL operator ==( const CString& s1, LPCTSTR s2 );
BOOL operator ==( LPCTSTR s1, const CString& s2 );
BOOL operator !=( const CString& s1, const CString& s2 );
BOOL operator !=( const CString& s1, LPCTSTR s2 );
BOOL operator !=( LPCTSTR s1, const CString& s2 );
BOOL operator <( const CString& s1, const CString& s2 );
BOOL operator <( const CString& s1, LPCTSTR s2 );
BOOL operator <( LPCTSTR s1, const CString& s2 );
BOOL operator >( const CString& s1, const CString& s2 );
BOOL operator >( const CString& s1, LPCTSTR s2 );
BOOL operator >( LPCTSTR s1, const CString& s2 );
BOOL operator <=( const CString& s1, const CString& s2 );
BOOL operator <=( const CString& s1, LPCTSTR s2 );
BOOL operator <=( LPCTSTR s1, const CString& s2 );
BOOL operator >=( const CString& s1, const CString& s2 );
BOOL operator >=( const CString& s1, LPCTSTR s2 );
BOOL operator >=( LPCTSTR s1, const CString& s2 );
    CString s1( "abc" );
    CString s2( "abd" );
    ASSERT( s1 < s2 ); // Operator is overloaded for both.
    ASSERT( "ABC" < s1 ); // CString and char*
    ASSERT( s2 > "abe" );
CompareCompares two strings (case sensitive).
int Compare( LPCTSTR lpsz ) const;
区分大小写比较两个字符串,相等时返回0,大于时返回1,小于时返回-1
    csStr="abcdef中文123456";
    csStr2="ABCDEF中文123456";
    cout<<csStr.Compare(csStr2);             //1
CompareNoCaseCompares two strings (case insensitive).
int CompareNoCase( LPCTSTR lpsz ) const;
不区分大小写比较两个字符串,相等时返回0,大于时返回1,小于时返回-1
    csStr="abcdef中文123456";
    csStr2="ABCDEF中文123456";
    cout<<csStr.CompareNoCase(csStr2);             //0
CollateCompares two strings (case sensitive, uses locale-specific information).
int Collate( LPCTSTR lpsz ) const;
CollateNoCaseCompares two strings (case insensitive, uses locale-specific information).
int CollateNoCase( LPCTSTR lpsz ) const;

Extraction

MidExtracts the middle part of a string (like the Basic MID$ function).
CString Mid( int nFirst ) const;
CString Mid( int nFirst, int nCount ) const;
从中间开始取字串
    csStr="abcdef";
    cout<<csStr.Mid(2);           //cdef
    csStr="abcdef";
    cout<<csStr.Mid(2,3);         //cde
当nFirst为0和为负数时,从第一个字符开始取。
当nFirst等于对象末尾时,返回空字串。
当nFirst超出对象末尾时,会发生无法预料的结果。
当nCount超出对象末尾时,返回从nFirst开始一直到对象末尾的字串
当nCount为0和为负数时,返回空字串。
LeftExtracts the left part of a string (like the Basic LEFT$ function).
CString Left( int nCount ) const;
从左取字串
    csStr="abcdef";
    cout<<csStr.Left(3);           //abc
当nCount等于0时,返回空。
当nCount为负数时,返回空。
当nCount大于对象长度时,返回值与对象相同。
RightExtracts the right part of a string (like the Basic RIGHT$ function).
CString Right( int nCount ) const;
从右取字串
    csStr="abcdef";
    cout<<csStr.Right(3);           //def
当nCount等于0时,返回空。
当nCount为负数时,返回空。
当nCount大于对象长度时,返回值与对象相同。
SpanIncludingExtracts a substring that contains only the characters in a set.
CString SpanIncluding( LPCTSTR lpszCharSet ) const;
从对象中查找与lpszCharSe中任意字符不匹配的字符,并返回第一个不匹配字符之前的字串
    csStr="abcdef";
    cout<<csStr.SpanIncluding("fdcba");    //abcd
SpanExcludingExtracts a substring that contains only the characters not in a set.
CString SpanExcluding( LPCTSTR lpszCharSet ) const;
返回对象中与lpszCharSet中任意匹配的第一个字符之前的子串
    csStr="abcdef";
    cout<<csStr.SpanExcluding("cf");    //ab

Other Conversions

MakeUpperConverts all the characters in this string to uppercase characters.
void MakeUpper( );
将小写字母转换为大写字母
    csStr="abcdef中文123456";
    csStr.MakeUpper();
    cout<<csStr;                  //ABCDEF中文123456
MakeLowerConverts all the characters in this string to lowercase characters.
void MakeLower( );
将大写字母转换为小写字母
    csStr="ABCDEF中文123456";
    csStr.MakeLower();
    cout<<csStr;                  //abcdef中文123456
MakeReverseReverses the characters in this string.
void MakeLower( );
将大写字母转换为小写字母
    csStr="Abcdef中文123456";
    csStr.MakeLower();
    cout<<csStr;                  //654321文中fedcbA
ReplaceReplaces indicated characters with other characters.
int Replace( TCHAR chOld, TCHAR chNew );
int Replace( LPCTSTR lpszOld, LPCTSTR lpszNew );
替换字串
    csStr="abcdef";
    csStr.Replace('a','x');
    cout<<csStr;                    //xbcdef
    csStr="abcdef";
    csStr.Replace("abc","xyz");
    cout<<csStr;                    //xyzdef
RemoveRemoves indicated characters from a string.
int Remove( TCHAR ch );
移除对象内的指定字符。返回移除的数目
    csStr="aabbaacc";
    csStr.Remove('a');
    cout<<csStr;                     //bbcc
InsertInserts a single character or a substring at the given index within the string.
int Insert( int nIndex, TCHAR ch )
int Insert( int nIndex, LPCTSTR pstr )
在下标为nIndex的位置,插入字符或字符串。返回插入后对象的长度
    csStr="abc";
    csStr.Insert(2,'x');
    cout<<csStr;                     //abxc
    csStr="abc";
    csStr.Insert(2,"xyz");
    cout<<csStr;                     //abxyzc
当nIndex为负数时,插入在对象开头
当nIndex超出对象末尾时,插入在对象末尾
DeleteDeletes a character or characters from a string.
int Delete( int nIndex, int nCount = 1 )
删除字符,删除从下标nIndex开始的nCount个字符
    csStr="ABCDEF";
    csStr.Delete(2,3);
    cout<<csStr;              // ABF
当nIndex过大,超出对像所在内存区域时,函数没有任何操作。
当nIndex为负数时,从第一个字符开始删除。
当nCount过大,导致删除字符超出对像所在内存区域时,会发生无法预料的结果。
当nCount为负数时,函数没有任何操作。
FormatFormat the string as sprintf does.
void Format( LPCTSTR lpszFormat, ... );
void Format( UINT nFormatID, ... );
格式化字符串:Format 方法,实现从 int、long 等数值类型、TCHAR、TCHAR * 等类型向 CString 类型的转换;
    int num = 6;
    CString str;
    str.Format("%d", num);
FormatVFormats the string as vsprintf does.
void FormatV( LPCTSTR lpszFormat, va_list argList );
TrimLeftTrim leading whitespace characters from the string.
void TrimLeft( );
void TrimLeft( TCHAR chTarget );
void TrimLeft( LPCTSTR lpszTargets );
从左删除字符,被删的字符与chTarget或lpszTargets匹配,一直删到第一个不匹配的字符为止
    csStr="aaabaacdef";
    csStr.TrimLeft('a');
    cout<<csStr;                //baacdef
    csStr="aaabaacdef";
    csStr.TrimLeft("ab");
    cout<<csStr;                //cdef
无参数时删除空格
TrimRightTrim trailing whitespace characters from the string.
void TrimRight( );
void TrimRight( TCHAR chTarget );
void TrimRight( LPCTSTR lpszTargets );
从右删除字符,被删的字符与chTarget或lpszTargets匹配,一直删到第一个不匹配的字符为止
    csStr="abcdeaafaaa";
    csStr.TrimRight('a');
    cout<<csStr;               //abcdeaaf
    csStr="abcdeaafaaa";
    csStr.TrimRight("fa");
    cout<<csStr;                //abcde
无参数时删除空格
FormatMessageFormats a message string.
void FormatMessage( LPCTSTR lpszFormat, ... );
void FormatMessage( UINT nFormatID, ... );
    CString str;
    int nAsked = 5;
    int nAgree = 4;
    str.FormatMessage(_T("%1!d! of %2!d! developers agree: Hockey is %3%!"), 
    nAgree, nAsked, _T("Best"));
    ASSERT(str == _T("4 of 5 developers agree: Hockey is Best!"));

Searching

FindFinds a character or substring inside a larger string.
int Find( TCHAR ch ) const;
int Find( LPCTSTR lpszSub ) const;
int Find( TCHAR ch, int nStart ) const;
int Find( LPCTSTR pstr, int nStart ) const;
查找字串,nStart为开始查找的位置。未找到匹配时返回-1,否则返回字串的开始位置
    csStr="abcdef";
    cout<<csStr.Find('b');       //1
    cout<<csStr.Find("de");      //3
    cout<<csStr.Find('b',3);     //-1
    cout<<csStr.Find('b',0);     //1
    cout<<csStr.Find("de",4);    //-1
    cout<<csStr.Find("de",0);    //3
当nStart超出对象末尾时,返回-1。
当nStart为负数时,返回-1。
ReverseFindFinds a character inside a larger string; starts from the end.
int ReverseFind( TCHAR ch ) const;
从后向前查找第一个匹配,找到时返回下标。没找到时返回-1
    csStr="abba";
    cout<<csStr.ReverseFind('a');        //3
FindOneOfFinds the first matching character from a set.
int FindOneOf( LPCTSTR lpszCharSet ) const;
查找lpszCharSet中任意一个字符在CString对象中的匹配位置。未找到时返回-1,否则返回字串的开始位置
    csStr="abcdef";
    cout<<csStr.FindOneOf("cxy");       //2

Archive/Dump

operator <<Inserts a CString object to an archive or dump context.
friend CArchive& operator <<( CArchive& ar, const CString& string );
throw( CArchiveException );
friend CArchive& operator >>( CArchive& ar, CString& string );
throw( CArchiveException );
friend CDumpContext& operator <<( CDumpContext& dc, const CString& string );
// example for CString::operator <<, >>
    extern CArchive ar;
    CString s( "abc" );
    #ifdef _DEBUG
    afxDump << s;  // Prints the value (abc)
    afxDump << &s;  // Prints the address
    #endif
    if( ar.IsLoading() )
        ar >> s;
    else
        ar << s;
operator >>Extracts a CString object from an archive.

Buffer Access

GetBufferReturns a pointer to the characters in the CString.
LPTSTR GetBuffer( int nMinBufLength );
申请新的空间,并返回指针
    csStr="abcde";
    LPTSTR pStr=csStr.GetBuffer(10);
    strcpy(pStr,"12345");
    csStr.ReleaseBuffer();
    pStr=NULL;
    cout<<csStr                 //12345
使用完GetBuffer后,必须使用ReleaseBuffer以更新对象内部数据,否则会发生无法预料的结果。
GetBufferSetLengthReturns a pointer to the characters in the CString, truncating to the specified length.
LPTSTR GetBufferSetLength( int nNewLength );
申请新的空间,并返回指针
    csStr="abc";
    csStr.GetBufferSetLength(20);
    cout<<csStr;                  //abc
    count<<csStr.GetLength();     //20;
    csStr.ReleaseBuffer();
    count<<csStr.GetLength();     //3;
使用GetBufferSetLength后可以不必使用ReleaseBuffer。
ReleaseBufferReleases control of the buffer returned by GetBuffer.
void ReleaseBuffer( int nNewLength = -1 );
使用GetBuffer后,必须使用ReleaseBuffer以更新对象内部数据
    csStr="abc";
    LPTSTR pStr=csStr.GetBuffer(10);
    strcpy(pStr,"12345");
    cout<<csStr.GetLength();       //3(错误的用法)
    csStr.ReleaseBuffer();
    cout<<csStr.GetLength();       //5(正确)
    pStr=NULL;
CString对象的任何方法都应在ReleaseBuffer之后调用
FreeExtraRemoves any overhead of this string object by freeing any extra memory previously allocated to the string.
调用此成员函数来释放先前已分配的不再需要的字符串,减少字符串对象消耗的内存开销。
#include <afx.h>
void PrintLengths(CString& str)
{
   printf("Alloc length is %d, String length is %d\n",
      str.GetAllocLength(), str.GetLength());
}
void main()
{
   // Create a CString with 1024 characters
   CString str('x', 1024);
   PrintLengths(str);


   // Assigning a smaller string won't cause CString to free its
   // memory, as it assumes the string will grow again anyway.
   str = _T("Hockey is Best!");
   PrintLengths(str);


   // This call forces CString to release the extra
   // memory it doesn't need.
   str.FreeExtra();
   PrintLengths(str);
}
Output
Alloc length is 1024, String length is 1024
Alloc length is 1024, String length is 15
Alloc length is 64, String length is  15
LockBufferDisables reference counting and protects the string in the buffer.
LPTSTR LockBuffer( );
UnlockBufferEnables reference counting and releases the string in the buffer.
void UnlockBuffer( );

Windows-Specific

AllocSysStringAllocates a BSTR from CString data.
BSTR AllocSysString ( ) const;
throw( CMemoryException );
    CString str("Hockey is Best!");
    BSTR bstr = str.AllocSysString();
// bstr now contains "Hockey is best", and can be
// passed to any OLE function requiring a BSTR.
// Normally, the function receiving the BSTR will
// free the string when it is done using it.
SetSysStringSets an existing BSTR object with data from a CString object.
BSTR SetSysString( BSTR* pbstr ) const;
// create an OLE string
    BSTR bstr = ::SysAllocString(L"Golf is fun!");
// create a CString and change the OLE
// string to the contents of the BSTR
    CString str("Hockey is best!");
    BSTR bstr2 = str.SetSysString(&bstr);
// Now, both bstr and bstr2 reference a single instance of
// the "Hockey" string. The "Golf" string has been freed.
    ASSERT(bstr2 == bstr);
LoadStringLoads an existing CString object from a Windows resource.
BOOL LoadString( UINT nID );
throw( CMemoryException );
return value:Nonzero if resource load was successful; otherwise 0.
remarks:Reads a Windows string resource, identified by nID, into an existing CString object. 
    #define IDS_FILENOTFOUND 1
    CString s;
    if (! s.LoadString( IDS_FILENOTFOUND ))
    {
        AfxMessageBox("Error Loading String: IDS_FILENOTFOUND");
        ...
    }
AnsiToOemMakes an in-place conversion from the ANSI character set to the OEM character set.
void AnsiToOem( );
OemToAnsiMakes an in-place conversion from the OEM character set to the ANSI character set.
void OemToAnsi( );

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值