MFC
2009.04.21 17:55

Cstring methods

조회 수 54917 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print
?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print

CString::GetLength

이 메소드는 CString 객체 안에 있는 캐릭터의 count를 반환한다.

이 count는 종료null문자를 포함하지 않는다.

// example for CString::GetLength
CString s( "abcdef" );
ASSERT( s.GetLength() == 6 );

 

CString::IsEmpty

이 메소드는 CString 객체가 비어있는지를 결정한다.

// example for CString::IsEmpty
CString s;
ASSERT( s.IsEmpty() );

 

CString::Empty

이 메소드는 CString객체를 비어있고 free memory로 만든다.

// example for CString::Empty
CString s( "abc" );
s.Empty();
ASSERT( s.GetLength( ) == 0 );

 

CString::GetAt

이 메소드는 인덱스넘버에의해 하나의문자를 반환한다.

// example for CString::GetAt
CString s( "abcdef" );
ASSERT( s.GetAt(2) == 'c' );

 

 

CString::SetAt

이 메소드는 인덱스넘버에 의해 지정받는 한문자를 덮어쓴다.

 

CString::Compare

이 메소드는 CString 객체와 다른 문자열을 Windows CE lstrcmp함수를 사용해서 비교한다.

// example for CString::Compare
CString s1( "abc" );
CString s2( "abd" );
ASSERT( s1.Compare( s2 ) == -1 ); // Compare with another CString.
ASSERT( s1.Compare( _T("abe" ) ) == -1 ); // Compare with LPTSTR string.

 

 

CString::CompareNoCase

이 메소드는 CStiring객체와 다른 문자열을 lstrcmpi 함수를 사용해서 비교한다.

(대문자가 상관없이 비교하는듯?...)

// example for CString::CompareNoCase
CString s1( "abc" );
CString s2( "ABD" );
ASSERT( s1.CompareNoCase( s2 ) == -1 ); // Compare with a CString.
ASSERT( s1.Compare( _T("ABE" ) ) == -1 ); // Compare with LPTSTR string.

 

 

CString::Mid

이 메소드는 CString 객체의 0위치부터 nCount의 부분문자열을 추출한다.

추출된 부분문자열을 복사해서 리턴한다.

인덱스가 zero base인것을 제외하고는 Basic MID함수와 비슷하다.

// example for CString::Mid
CString s( _T("abcdef") );
ASSERT( s.Mid( 2, 3 ) == _T("cde") );

 

CString::Left

왼쪽부터 nCount의 문자열을 추출~

// example for CString::Left
CString s( _T("abcdef") );
ASSERT( s.Left(2) == _T("ab") );

 

CString::Right

오른쪽부터 nCount의 문자열을 추출~

// example for CString::Right
CString s( _T("abcdef") );
ASSERT( s.Right(2) == _T("ef") );

 

CString::SpanIncluding

이 메소드는 문자열로부터 문자를 추출하고, lpszCharSet에의해 확인된 문자열의

첫번째 문자부터 시작한다.

만약 string의 첫번째 문자가 문자셋에 없으면 SpanIncluding은 empty string을 리턴한다.

그렇지 않다면 set안에 있는 연속적인 문자열을 연속으로 리턴한다.

// example for CString::SpanIncluding
CString str( "cabbage" );
CString res = str.SpanIncluding( _T("abc") );
ASSERT( res == "cabba" );
res = str.SpanIncluding( _T("xyz") );
ASSERT( res.IsEmpty( ) );

 

CString::SpanExcluding

This method searches the string for the first occurrence of any character in the specified set lpszCharSet. SpanExcluding extracts and returns all characters preceding the specified character set. In other words, the specified character set, and all characters following it in the string, are not returned. If the specified character set is not found in the string, then SpanExcluding returns an empty string.(이해못함)

// Portions are delimited by a semicolon( ; ),
//  a comma( , ), a period( . ), a dash( - ),
// or a colon( : ).

CString GetFirstPart( CString src)
{
    return src.SpanExcluding( _T(";,.- :"));
}

 

CString::MakeUpper

이 메소드는 CString 객체를 대문자로 바꾼다.

// example for CString::MakeUpper
CString s( "abc" );
s.MakeUpper();
ASSERT( s == "ABC" );

 

CString::MakeLower

소문자를 대문자로~

// example for CString::MakeLower
CString s( "ABC" );
s.MakeLower();
ASSERT( s == "abc" );

 

CString::MakeReverse

앞뒤를 바꺼바꺼~

// example for CString::MakeReverse
CString s( "abc" );
s.MakeReverse();
ASSERT( s == "cba" );

 

CString::Format

이 메소드는 sprintf 포맷이 데이타를 C-style 캐릭터배열로 포맷하는것과 같은 방법으로

데이타를 쓴다.

일련의 문자열과 CString안의 값을 포맷하고 저장한다?...

잘모르겠음~

CString str;

str.Format(_T("Floating point: %.2f\n"), 12345.12345);
_tprintf(_T("%s"), (LPCTSTR) str);

str.Format(_T("Left-justified integer: %.6d\n"), 35);
_tprintf(_T("%s"), (LPCTSTR) str);

str.Format(IDS_SCORE, 5, 3);
_tprintf(_T("%s"), (LPCTSTR) str);

 

CString::TrimLeft

이 메소드는 줄이나,빈칸,탭을 삭제한다.

 

CString strBefore;
CString strAfter;

strBefore = _T("\t\t   ****Hockey is best!");
strAfter = strBefore;
strAfter.TrimLeft(T_("\t *"));//\t와 *를 삭제하는듯.

_tprintf(_T("Before: \"%s\"\n"), (LPCTSTR) strBefore); //"\t\t ****Hockey is best!"

_tprintf(_T("After : \"%s\"\n"), (LPCTSTR) strAfter);     //"Hockey is best!"

 

 

CString::TrimRight

역시 오른쪽의 선언한것들을 삭제하는듯

CString strBefore;
CString strAfter;

  strBefore = "Hockey is Best!!!!";
  strAfter = strBefore;
  str.TrimRight('!');
  _tprintf("Before: \"%s\"\n", (LPCTSTR) strBefore);
  _tprintf("After : \"%s\"\n\n", (LPCTSTR) strAfter);

  strBefore = "Hockey is Best?!?!?!?!";
  strAfter = strBefore;
  str.TrimRight("?!");
  _tprintf("Before: \"%s\"\n", (LPCTSTR) strBefore);
  _tprintf("After : \"%s\"\n\n", (LPCTSTR) strAfter);

CString::Find

이 메소드는 부분문자열의 첫번째 매치되는 문자를 조사한다.

// First example demonstrating
// CString::Find ( TCHAR ch )
CString s( "abcdef" );
ASSERT( s.Find( 'c' ) == 2 );
ASSERT( s.Find( _T("de" ) ) == 3 );

// Second example demonstrating
// CString::Find( TCHAR ch, int nStart )
CString str("The stars are aligned");
int n = str.Find('e', 5);
ASSERT(n == 12);

 

CString::ReverseFind

뒤에서 부터 찾는듯~

// Example for CString::ReverseFind
CString s( "abcabc" );
ASSERT( s.ReverseFind( 'b' ) == 4 );

 

CString::FindOneOf

이 메소드는 lpszCharSet안에 포함된 어떤문자라도 매치되는 첫번째 문자를 찾기위해 조사한다.

// example for CString::FindOneOf
CString s( "abcdef" );
ASSERT( s.FindOneOf( _T( "xd" ) ) == 3 ); // 'd' is first match x는없고d는 있으니 d를 찾은듯.

 

 

CString::GetBuffer

이 메소드는 CStirng 객에의 내부의 캐릭터버퍼의 포인터를 되찾는다.

LPTSTR은 const로 리턴되지않고 CStirng 목차안의 직접수정을 허락한다.

만약 nMinBufLength가 현재 버터의 길이보다 크면 GetBuffer가콜되어 현재의 버퍼를파괴할것이다

그것을 요청된 사이즈의 버퍼로 바꾸고, 카운트를 zero로 고쳐라?..

만약 당신이 이버퍼위에 LockBuffer를 콜했다면 당신은 버퍼의 lock을 잃어버릴것이다.

// example for CString::GetBuffer
CString s( "abcd" );
#ifdef _DEBUG
afxDump << "CString s " << s << "\n";
#endif
LPTSTR p = s.GetBuffer( 10 );
lstrcpy( p, _T("Hello") );  // directly access CString buffer
s.ReleaseBuffer( );
#ifdef _DEBUG
afxDump << "CString s " << s << "\n";
#endif

CString::GetBufferSetLength

이 방법은 CStirng 객체의 내부의 캐릭터 버터의 포인터를 반환하고

필요하다면 nNewLength에서 지정받는 길이와 정확히 맞추기위해 , 그것의 길이를 끊거나

증가한다.

CString str;
LPTSTR pstr = str.GetBufferSetLength(3);
pstr[0] = 'I';
pstr[1] = 'c';
pstr[2] = 'e';

// No need for trailing zero or call to ReleaseBuffer()
// because GetBufferSetLength() set it for us!

str += _T(" hockey is best!");

 

CString::ReleaseBuffer

이 메소드는 GetBuffer에 의해 할당된 버퍼를 해체한다.

만약 당신이 버퍼스트링이 널로 끝난다는 것을 알면 당신은 nNewLength 파라미터를 생략할수있다

만일 당신의 스트링이 널로 안끝나면 그 길이를 지정하기위해 nNewLength를 사용해라.

GetBuffer에 의해 리턴된 주소는 ReleaseBuffer나 다른 어떤 CString operation이 콜되도 무효하다

// example for CString::ReleaseBuffer
CString s;
s = "abc";
LPTSTR p = s.GetBuffer( 1024 );
strcpy(p, "abc");  // use the buffer directly
ASSERT( s.GetLength() == 3 ); // String length = 3
s.ReleaseBuffer();  // Surplus memory released, p is now invalid.
ASSERT( s.GetLength() == 3 ); // Length still 3

 

 

CString::FreeExtra

This method frees any extra memory previously allocated by the string but no longer needed. This should reduce the memory overhead consumed by the string object. The method reallocates the buffer to the exact length returned by GetLength.

#include <afx.h>

void PrintLengths(CString& str)
{
   _tprintf("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

 

CString::LockBuffer

버터의 string을 락시킴;

 

 

CString::UnlockBuffer

락된 버터를 언락시킴- _-;

 

 

CString::AllocSysString

이 방법은 새로운 BSTR 타입의 새로운 Automation 을 할당하고 CString 객체의 목차를 복사하고

종료의 널문자를 포함한다.

CMemoryException는 만약 불충분한 메모리가 존재하면 던져진다?;;

이 메소드는 Automation한 스트링을 반환하기 위해 일반적으로 사용된다.

CString::AllocSysString

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.

 

CString::SetSysString

이 메소드는 pbstr에의해 참조되는 BSTR을 재할당하고 널 문자를 포함하는 CString 객체의 목차를 카피한다. pbstr에 의해 참조되는 BSTR의 값은 바뀔수도 있다.이 메소드는 만약 불충분한 메모리가 존재하면 CMemoryException을 던진다?;

이 메소드는 통상 OLE Automation의 참조에 의해 통과되는 문자열의 값을 바꾸기위해 사용된다.

// 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);

 

CString::LoadString

이 메소드는 Windows CE 스트링 리소스를 읽고 기존의 CString 객체에 nID로 확인된다.

// example for CString::LoadString
#define IDS_FILENOTFOUND 1
CString s;
if (! s.LoadString( IDS_FILENOTFOUND ))
{
    AfxMessageBox("Error Loading String: IDS_FILENOTFOUND");
    ...
}

 

수업시간에 과제로 나온 MSDN 번역... 고생했던 기억이 납니다 ㅋ

[출처] Cstring methods|작성자 바이브


CString class
 

CString CObject에서 상속을 받지않고 Simple Value Types 하나이다.

CString object 문자들의 가변적인 길이의 연속으로 구성되고, 문자 배열보다 사용하기가 쉽다. CString TCHAR 데이터 타입을 기초로 하고 있다.

 

n          CString Class Members

 

Ø         Construction

CString   -              CString 생성자 ( CString :: CString )

CString( );

CString( const CString& stringSrc );                throw( CMemoryException );

CString( TCHAR ch, int nRepeat = 1 );              throw( CMemoryException );

CString( LPCTSTR lpch, int nLength );              throw( CMemoryException );

CString( const unsigned char* psz );              throw( CMemoryException );

CString( LPCWSTR lpsz );                            throw( CMemoryException );

CString( LPCSTR lpsz );                              throw( CMemoryException );

 

Example

// example for CString::CString

CString s1;                    // Empty string

CString s2( "cat" );           // From a C string literal

CString s3 = s2;               // Copy constructor

CString s4( s2 + " " + s3 );   // From a string expression

CString s5( 'x' );             // s5 = "x"

CString s6( 'x', 6 );          // s6 = "xxxxxx"

CString s7((LPCSTR)ID_FILE_NEW); // s7 = "Create a new document"

CString city = "Philadelphia"; // NOT the assignment operator

 

Ø         The String as an Array

GetLength : 설정된 문자열의 길이를 리턴

int GetLength( ) const;

IsEmpty  : 문자열의 버퍼가 비워져 있는지를 검사

BOOL IsEmpty( ) const;

Empty : 문자열을 삭제하여 버퍼를 비운다.

void Empty( );

GetAt : 특정위치의 문자값을 얻는다.

TCHAR GetAt( int nIndex ) const;

operator []              

TCHAR operator []( int nIndex ) const

SetAt

void SetAt( int nIndex, TCHAR ch );

operator LPCTSTR 

operator LPCTSTR ( ) const;

 

Ø         Assignment / Concatenation

Operator =

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 );

 

Operator +

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 );

 

Operator +=

const CString& operator +=( const CString& string );                         throw( CMemoryException );

const CString& operator +=( TCHAR ch );                                       throw( CMemoryException );

const CString& operator +=( LPCTSTR lpsz );                                    throw( CMemoryException );

 

 

 

Ø         Comparison

Operator == <, etc

Compare : 대소문자 구분

int Compare( LPCTSTR lpsz ) const;

CompareNoCase : 대소문자 구분 안함

int CompareNoCase( LPCTSTR lpsz ) const;

Collate

int Collate( LPCTSTR lpsz ) const

CollateNoCase

int CollateNoCase( LPCTSTR lpsz ) const;

 

Ø         Extraction

Mid : 문자열의 중간부분을 추출한다.

CString Mid( int nFirst ) const;                throw( CMemoryException );

CString Mid( int nFirst, int nCount ) const;        throw( CMemoryException );

Left : 문자열의 왼쪽부분은 추출한다.

CString Left( int nCount ) const;                throw( CMemoryException );

Right : 문자열의 오른쪽부분을 추출한다.

CString Right( int nCount ) const;                throw( CMemoryException );

SpanIncluding :             포함된 문자를 추출

CString SpanIncluding( LPCTSTR lpszCharSet ) const        throw( CMemoryException );

SpanExcluding

CString SpanExcluding( LPCTSTR lpszCharSet ) const;        throw( CMemoryException );

 

Ø         Other Conversions

MakeUpper : 소문자를 대문자로 바꾼다.

void MakeUpper( );

MakeLower : 대문자를 소문자로 바꾼다.

void MakeLower( );

MakeReverse : 문자를 reverse 시킨다.

void MakeReverse( );

Replace

int Replace( TCHAR chOld, TCHAR chNew );

int Replace( LPCTSTR lpszOld, LPCTSTR lpszNew );

Remove : 문자를 제거한다.

int CString::Remove( TCHAR ch );

Insert

int Insert( int nIndex, TCHAR ch )    throw( CMemoryException );

int Insert( int nIndex, LPCTSTR pstr )  throw( CMemoryException );

Delete

int Delete( int nIndex, int nCount = 1 )  throw( CMemoryException );

Format : sprintf 비슷하다.

void Format( LPCTSTR lpszFormat, ... );

void Format( UINT nFormatID, ... );

FormatV

void FormatV( LPCTSTR lpszFormat, va_list argList );

TrimLeft

void TrimLeft( );

void CString::TrimLeft( TCHAR chTarget );

void CString::TrimLeft( LPCTSTR lpszTargets );

TrimRight

void TrimRight( );

void CString::TrimRight( TCHAR chTarget );

void CString::TrimRight( LPCTSTR lpszTargets );

FormatMessage

void FormatMessage( LPCTSTR lpszFormat, ... );

void FormatMessage( UINT nFormatID, ... );

 

Ø         Serching

Find : 문자의 인덱스를 찾아 반환한다.

int Find( TCHAR ch ) const;

int Find( LPCTSTR lpszSub ) const;

int Find( TCHAR ch, int nStart ) const;

int Find( LPCTSTR pstr, int nStart ) const;

ReverseFind : 뒤에서부터 찾는다.

int ReverseFind( TCHAR ch ) const;

FindOneOf

int FindOneOf( LPCTSTR lpszCharSet ) const;

 

 

Ø         Archive / Dump

Operator <<, Operator >>

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 );

 

Ø         Buffer Access

GetBuffer

LPTSTR GetBuffer( int nMinBufLength );  throw( CMemoryException );

GetBufferSetLength

LPTSTR GetBufferSetLength( int nNewLength ); throw( CMemoryException );

ReleaseBuffer

void ReleaseBuffer( int nNewLength = -1 );

FreeExtra

void FreeExtra( );

LockBuffer             

LPTSTR LockBuffer( );

UnlockBuffer

void UnlockBuffer( )

[출처] CString|작성자 하얀악마


====================
 MSDN 내용
====================

Constructors/Destructors

CStringT Constructs a CStringT object in various ways.
~CStringT Destroys a CStringT object.

Methods

AllocSysString Allocates a BSTR from CStringT data.
AnsiToOem Makes an in-place conversion from the ANSI character set to the OEM character set.
AppendFormat Appends formatted data to an existing CStringT object.
Collate Compares two strings (case sensitive, uses locale-specific information).
CollateNoCase Compares two strings (case insensitive, uses locale-specific information).
Compare Compares two strings (case sensitive).
CompareNoCase Compares two strings (case insensitive).
Delete Deletes a character or characters from a string.
Find Finds a character or substring inside a larger string.
FindOneOf Finds the first matching character from a set.
Format Formats the string as sprintf does.
FormatMessage Formats a message string.
FormatMessageV Formats a message string using a variable argument list.
FormatV Formats the string using a variable list of arguments.
GetEnvironmentVariable Sets the string to the value of the specified environment variable.
Insert Inserts a single character or a substring at the given index within the string.
Left Extracts the left part of a string.
LoadString Loads an existing CStringT object from a Windows resource.
MakeLower Converts all the characters in this string to lowercase characters.
MakeReverse Reverses the string.
MakeUpper Converts all the characters in this string to uppercase characters.
Mid Extracts the middle part of a string.
OemToAnsi Makes an in-place conversion from the OEM character set to the ANSI character set.
Remove Removes indicated characters from a string.
Replace Replaces indicated characters with other characters.
ReverseFind Finds a character inside a larger string; starts from the end.
Right Extracts the right part of a string.
SetSysString Sets an existing BSTR object with data from a CStringT object.
SpanExcluding Extracts characters from the string, starting with the first character, that are not in the set of characters identified by pszCharSet.
SpanIncluding Extracts a substring that contains only the characters in a set.
Tokenize Extracts specified tokens in a target string.
Trim Trims all leading and trailing whitespace characters from the string.
TrimLeft Trims leading whitespace characters from the string.
TrimRight Trims trailing whitespace characters from the string.

Operators

operator = Assigns a new value to a CStringT object.
operator + Concatenates two strings or a character and a string.
operator += Concatenates a new string to the end of an existing string.
operator == Determines if two strings are logically equal.
operator != Determines if two strings are logically not equal.
operator < Determines if the string on the left side of the operator is less than to the string on the right side.
operator > Determines if the string on the left side of the operator is greater than to the string on the right side.
operator <= Determines if the string on the left side of the operator is less than or equal to the string on the right side.
operator >= Determines if the string on the left side of the operator is greater than or equal to the string on the right side.

See Also

CStringT Overview


Dreamy의 코드 스크랩

내가 모으고 내가 보는

List of Articles
번호 분류 제목 날짜 조회 수 추천 수
31 MFC MFC에서 인자(argument)처리 2005.10.28 47020 0
30 MFC 다이얼로그 기반 APP에서 Edit에 엔터키 먹게 하기 2006.04.14 42091 0
29 MFC CString을 유니코드로 변환 WCHAR에 저장하는 방법 1 2006.04.14 56713 0
28 MFC API를 이용하는 유니코드와 ANSI 문자열간의 변환 방법 2006.04.14 63085 0
27 MFC [C] Unicode 사용에 대하여 2006.04.14 47078 0
26 MFC 시작프로그램 레지스트리에 등록/해제 함수 2006.04.14 45687 0
25 MFC 노트패드를 이용한 덤프 file 2006.05.19 33501 0
24 MFC 시스템 출력 리디렉션 - 도스 커맨드 결과 받아오기 file 2007.08.14 52866 0
23 MFC 리사이징 다이얼로그(Resizing dialog) 2008.03.24 46616 0
22 MFC 현재 실행된 어플리케이션의 디렉토리 적용하기 2008.05.07 39881 0
21 MFC 현재디렉토리의 파일리스트들을 알아오는 클래스 CFindFile 2008.05.07 62447 0
20 MFC 비트맵 비교 2009.03.23 40812 0
» MFC Cstring methods 2009.04.21 54917 0
18 MFC 도스 커맨드 실행하기 1 2009.09.01 49039 0
17 MFC 커맨드 창 속성 제어 2009.09.01 37885 0
목록
Board Pagination ‹ Prev 1 2 3 Next ›
/ 3

나눔글꼴 설치 안내


이 PC에는 나눔글꼴이 설치되어 있지 않습니다.

이 사이트를 나눔글꼴로 보기 위해서는
나눔글꼴을 설치해야 합니다.

설치 취소

Designed by sketchbooks.co.kr / sketchbook5 board skin

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5