Студопедия

КАТЕГОРИИ:

АвтоАвтоматизацияАрхитектураАстрономияАудитБиологияБухгалтерияВоенное делоГенетикаГеографияГеологияГосударствоДомЖурналистика и СМИИзобретательствоИностранные языкиИнформатикаИскусствоИсторияКомпьютерыКулинарияКультураЛексикологияЛитератураЛогикаМаркетингМатематикаМашиностроениеМедицинаМенеджментМеталлы и СваркаМеханикаМузыкаНаселениеОбразованиеОхрана безопасности жизниОхрана ТрудаПедагогикаПолитикаПравоПриборостроениеПрограммированиеПроизводствоПромышленностьПсихологияРадиоРегилияСвязьСоциологияСпортСтандартизацияСтроительствоТехнологииТорговляТуризмФизикаФизиологияФилософияФинансыХимияХозяйствоЦеннообразованиеЧерчениеЭкологияЭконометрикаЭкономикаЭлектроникаЮриспунденкция

Некоторые полезные функции класса CString




CString::Compare

int Compare( LPCTSTR lpsz ) const;

Return Value

Zero if the strings are identical, < 0 if this CString object is less than lpsz, or > 0 if this CString object is greater than lpsz.

Parameters

lpsz

The other string used for comparison.

Remarks

Compares this CString object with another string using the generic-text function _tcscmp. The generic-text function _tcscmp, which is defined in TCHAR.H, maps to either strcmp, wcscmp, or _mbscmp depending on the character set that is defined at compile time. Each of these functions performs a case-sensitive comparison of the strings, and is not affected by locale. For more information, see https://msdn.microsoft.com/en-us/library/e0z9k731(v=vs.60).aspx in the Run-Time Library Reference.

Example

The following example demonstrates the use of CString::Compare.

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

See Also CString::CompareNoCase, CString::Collate, CString::CollateNoCase

CStringT::Delete

Deletes a character or characters from a string starting with the character at the given index.

int Delete( int iIndex, int nCount = 1); Parameters

iIndex

The zero-based index of the first character in the CStringT object to delete.

nCount

The number of characters to be removed.

Return Value

The length of the changed string.

Remarks

If nCount is longer than the string, the remainder of the string will be removed.

Example CAtlString str(_T("Soccer is best, but liquor is quicker!"));_tprintf_s(_T("Before: %s\n"), (LPCTSTR)str); int n = str.Delete(6, 3);_tprintf_s(_T("After: %s\n"), (LPCTSTR)str);ASSERT(n == str.GetLength());

CString::Empty

void Empty( );

Remarks

Makes this CString object an empty string and frees memory as appropriate.

For more information, see n Visual C++ Programmer’s Guide

Example

The following example demonstrates the use of CString::Empty.

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

See Also CString::IsEmpty

 

CString::Find

int Find( TCHAR ch ) const;

int Find( LPCTSTR lpszSub ) const;

int Find( TCHARch, intnStart) const;

int Find( LPCTSTRpstr, intnStart) const;

Return Value

The zero-based index of the first character in this CString object that matches the requested substring or characters; -1 if the substring or character is not found.

Parameters

ch

A single character to search for.

lpszSub

A substring to search for.

nStart

The index of the character in the string to begin the search with, or 0 to start from the beginning. The character at nStart is excluded from the search if nStart is not equal to 0.

pstr

A pointer to a string to search for.

Remarks

Searches this string for the first match of a substring. The function is overloaded to accept both single characters (similar to the run-time function strchr) and strings (similar to strstr).

Example

// First example demonstrating// CString::Find ( TCHAR ch )CString s( "abcdef" );ASSERT( s.Find( 'c' ) == 2 );ASSERT( s.Find( "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); See Also CString::ReverseFind, CString::FindOneOf

 

CString::Left

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


Return Value

A CString object containing a copy of the specified range of characters. Note that the returned CString object may be empty.

Parameters

nCount

The number of characters to extract from this CString object.

Remarks

Extracts the first (that is, leftmost) nCount characters from this CString object and returns a copy of the extracted substring. If nCount exceeds the string length, then the entire string is extracted. Left is similar to the Basic LEFT$ function (except that indexes are zero-based).

For multibyte character sets (MBCS), nCount refers to each 8-bit character; that is, a lead and trail byte in one multibyte character are counted as two characters.

Example

The following example demonstrates the use of CString::Left.

// example for CString::LeftCString s( _T("abcdef") );ASSERT( s.Left(2) == _T("ab") ); See Also CString::Mid, CString::Right

CString::Mid

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

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



Return Value

A CString object that contains a copy of the specified range of characters. Note that the returned CString object may be empty.

Parameters

nFirst

The zero-based index of the first character in this CString object that is to be included in the extracted substring.

nCount

The number of characters to extract from this CString object. If this parameter is not supplied, then the remainder of the string is extracted.

Remarks

Extracts a substring of length nCount characters from this CString object, starting at position nFirst (zero-based). The function returns a copy of the extracted substring. Mid is similar to the Basic MID$ function (except that indexes are zero-based).

For multibyte character sets (MBCS), nCount refers to each 8-bit character; that is, a lead and trail byte in one multibyte character are counted as two characters.

Example

The following example demonstrates the use of CString::Mid.

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

CString::Remove

int CString::Remove( TCHARch);

Return Value

The count of characters removed from the string. Zero if the string isn't changed.

Parameters

ch

The character to be removed from a string.

Remarks

Call this member function to remove instances of ch from the string. Comparisons for the character are case-sensitive.

Example

//remove the lower-case letter 't' from a sentence: CString str("This is a test.");int n = str.Remove('t');ASSERT(n == 2);ASSERT(str == "This is a es.");See Also CString::Replace

CString::Replace

int Replace( TCHARchOld, TCHARchNew);

int Replace( LPCTSTRlpszOld, LPCTSTRlpszNew);

Return Value

The number of replaced instances of the character. Zero if the string isn't changed.

Parameters

chOld

The character to be replaced by chNew.

chNew

The character replacing chOld.

lpszOld

A pointer to a string containing the character to be replaced by lpszNew.

lpszNew

A pointer to a string containing the character replacing lpszOld.

Remarks

Call this member function to replace a character with another. The first prototype of the function replaces instances of chOld with chNew in-place in the string. The second prototype of the function replaces instances of the substring lpszOld with instances of the string lpszNew.

The string may grow or shrink as a result of the replacement; that is, lpszNew and lpszOld do not have to be equal in length. Both versions perform case-sensitive matches.

Example

//First example, with old and new equal in length. CString strZap("C--");int n = strZap.Replace('-', '+');ASSERT(n == 2);ASSERT(strZap == "C++"); //Second example, old and new are of different lengths. CString strBang("Everybody likes ice hockey");n = strBang.Replace("hockey", "golf");ASSERT(n == 1);n = strBang.Replace("likes", "plays");ASSERT(n == 1);n = strBang.Replace("ice", NULL);ASSERT(n == 1);ASSERT(strBang == "Everybody plays golf"); // note that you now have an extra space in your// sentence. To remove the extra space, include it// in the string to be replaced, i.e.,"ice ". See Also CString::Remove

CString::ReverseFind

int ReverseFind( TCHAR ch ) const;

Return Value

The index of the last character in this CString object that matches the requested character; –1 if the character is not found.

Parameters

ch

The character to search for.

Remarks

Searches this CString object for the last match of a substring. The function is similar to the run-time function strrchr.

Example

// Example for CString::ReverseFindCString s( "abcabc" );ASSERT( s.ReverseFind( 'b' ) == 4 ); See Also CString::Find, CString::FindOneOf

CString::Right

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


Return Value

A CString object that contains a copy of the specified range of characters. Note that the returned CString object may be empty.

Parameters

nCount

The number of characters to extract from this CString object.

Remarks

Extracts the last (that is, rightmost) nCount characters from this CString object and returns a copy of the extracted substring. If nCount exceeds the string length, then the entire string is extracted. Right is similar to the Basic RIGHT$ function (except that indexes are zero-based).

For multibyte character sets (MBCS), nCount refers to each 8-bit character; that is, a lead and trail byte in one multibyte character are counted as two characters.

Example

The following example demonstrates the use of CString::Right.

// example for CString::RightCString s( _T("abcdef") );ASSERT( s.Right(2) == _T("ef") ); See Also CString::Mid, CString::Left

CString::SetAt

void SetAt( int nIndex, TCHAR ch );

Parameters

nIndex

Zero-based index of the character in the CString object. The nIndex parameter must be greater than or equal to 0 and less than the value returned by GetLength. The Debug version of the Microsoft Foundation Class Library will validate the bounds of nIndex; the Release version will not.

ch

The character to insert.

Remarks

You can think of a CString object as an array of characters. The SetAt member function overwrites a single character specified by an index number. SetAt will not enlarge the string if the index exceeds the bounds of the existing string.

See Also CString::GetAt, CString::operator [ ]

CString::SetSysString

BSTR SetSysString( BSTR* pbstr ) const;

Return Value

The new string.

Parameters

pbstr

A pointer to a character string.

Remarks

Reallocates the BSTR pointed to by pbstr and copies the contents of the CString object into it, including the NULL character. The value of the BSTR referenced by pbstr may change. The function throws a CMemoryException if insufficient memory exists.

This function is normally used to change the value of strings passed by reference for OLE Automation.

For more information about OLE reallocation functions in Windows, see https://msdn.microsoft.com/en-us/library/ms221533(v=vs.60).aspx and https://msdn.microsoft.com/en-us/library/ms221481(v=vs.60).aspx in the Win32 SDK OLE Programmer’s Referenc.

Example

// create an OLE stringBSTR bstr = ::SysAllocString(L"Golf is fun!"); // create a CString and change the OLE// string to the contents of the BSTRCString 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 Overview | Class Members | Hierarchy Chart

CString::SpanExcluding

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


Return Value

A substring that contains characters in the string that are not in lpszCharSet, beginning with the first character in the string and ending with the first character found in the string that is also in lpszCharSet (that is, starting with the first character in the string and up to but excluding the first character in the string that is found lpszCharSet). It returns the entire string if no character in lpszCharSet is found in the string.

Parameters

lpszCharSet

A string interpreted as a set of characters.

Remarks

Use this function to search the string for the first occurrence of any character in the specified set lpszCharSet. SpanExcluding extracts and returns all characters preceding the first occurrence of a character from lpszCharSet (in other words, the character from lpszCharSet and all characters following it in the string, are not returned). If no character from lpszCharSet is found in the string, then SpanExcluding returns the entire string.

Example

The following function returns the first portion of the src param.

// Portions are delimited by a semi-colon( ; ),

// a comma( , ), a period( . ), a dash( - ),

// or a colon( : ).

 

CString GetFirstPart( CString src)

{

return src.SpanExcluding( ";,.- :");

}

 

See Also CString::SpanIncluding

CString::SpanIncluding

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


Return Value

A substring that contains characters in the string that are in lpszCharSet, beginning with the first character in the string and ending when a character is found in the string that is not in lpszCharSet. SpanIncluding returns an empty substring if the first character in the string is not in the specified set.

Parameters

lpszCharSet

A string interpreted as a set of characters.

Remarks

Call this member function to extract characters from the string, starting with the first character, that are in the set of characters identified by lpszCharSet. If the first character of the string is not in the character set, then SpanIncluding returns an empty string. Otherwise, it returns a sequence of consecutive characters which arein the set.

Example

The following example demonstrates the use of CString::SpanIncluding.

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

CString::TrimLeft

void TrimLeft( );

void CString::TrimLeft( TCHARchTarget);

void CString::TrimLeft( LPCTSTRlpszTargets);

Parameters

chTarget

The target characters to be trimmed.

lpszTargets

A pointer to a string containing the target characters to be trimmed.

Remarks

Call the version of this member function with no parameters to trim leading whitespace characters from the string. When used with no parameters, TrimLeft removes newline, space, and tab characters.

Use the versions of this function that accept parameters to remove a particular character or a particular group of characters from the beginning of a string.

For more information, see in Visual C++ Programmer’s Guide

Example

In this example, the string "\t\t ****Hockey is best!" becomes "Hockey is best!":

CString strBefore;CString strAfter; strBefore = _T("\t\t ****Hockey is best!");strAfter = strBefore;strAfter.TrimLeft(T_("\t *")); _tprintf(_T("Before: \"%s\"\n"), (LPCTSTR) strBefore);_tprintf(_T("After : \"%s\"\n"), (LPCTSTR) strAfter); See Also CString::Mid, CString::Left, CString::Right, CString::MakeUpper, CString::MakeLower, CString::MakeReverse, CString::Format

CString::TrimRight

void TrimRight( );

void CString::TrimRight( TCHARchTarget);

void CString::TrimRight( LPCTSTRlpszTargets);

Parameters

chTarget

The target characters to be trimmed.

lpszTargets

A pointer to a string containing the target characters to be trimmed.

Remarks

Call the version of this member function with no parameters to trim trailing whitespace characters from the string. When used with no parameters, TrimRight removes trailing newline, space, and tab characters from the string.

Use the versions of this function that accept parameters to remove a particular character or a particular group of characters from the end of a string.

Example

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

In the first example above, the string reading, "Hockey is Best!!!!" becomes "Hockey is Best".

In the second example above, the string reading, , "Hockey is Best?!?!?!?!" becomes "Hockey is Best".

For more information, see in Visual C++ Programmer’s Guide

See Also CString::TrimLeft, CString::Mid, CString::Left, CString::Right, CString::MakeUpper, CString::MakeLower, CString::MakeReverse, CString::Format

Явное преобразование типов

В данном подразделе использован материал из раздела 6.2.7 [3].

Явным преобразованием или приведением типа называют преобразование переменной, выражения и т.п. из одного типа в другой. В языке С такое преобразование применялось, например, в следующем виде:

void *p;

// …

char *s=(char *)p;

 

Подобное преобразование типа является небезопасным, так как компилятор не знает, корректно ли значение p и не может его проверить. Следовательно, такое преобразование является потенциальным источником ошибок, хотя в некоторых случаях оно полезно.

Для снижения вероятности совершения ошибок, связанных с приведением типа, в языке С++ введены следующие операции приведения типа:

· dynamic_cast – для преобразования полиморфных типов;

· static_cast – для преобразования неполиморфных типов;

· const_cast –для удаления атрибутов const, volatile и __unaligned;

· reinterpret_cast – для преобразования любого интегрального типа в указатель и наоборот;

· safe_cast – используется на платформе .NET для получения верифицируемого MSIL-кода.

 

Вы можете использовать преобразования const_cast и reinterpret_cast как самое крайнее средство, так как эти операции так же небезопасны, как и преобразования в стиле С. Тем не менее, они необходимы для того, чтобы полностью заменить преобразование типов в старом стиле.

Операция static_cast осуществляет преобразование родственных типов, например, указателя на один класс в указатель на другой тип из той же иерархии классов, перечислений в целые типы или типа с плавающей точкой в интегральный.

Операция reinterpret_cast управляет преобразованиями между несвязанными типами, например, целых в указатели или указателей в другие (несвязанные) указатели.

Такое различие между операциями static_cast и reinterpret_cast позволяет компилятору осуществлять минимальную проверку типов при static_cast, а программисту – легче обнаружить опасные преобразования, представляемые reinterpret_cast. Некоторые преобразования static_cast являются переносимыми, но reinterpret_cast практически никогда непереносимы. Хотя никаких гарантий относительно reinterpret_cast дать нельзя, в результате обычно получается значение нового типа, состоящее из той же цепочки бит, что и аргумент. То, что результатом пребразования reinterpret_cast можно пользоваться, гарантировано только если тип его результата есть в точности тип, использованный для определения задействованного в преобразовании значения. Обратите внимание, что reinterpret_cast является той разновидностью преобразования, которой следует пользоваться при работе с указателями на функции.

Если у Вас возникло искушение пользоваться явным преобразованием, задумайтесь над тем, так ли это необходимо. В большинстве случаев в С++ нет нужды в явном преобразовании типов даже тогда, когда это необходимо в С или в более ранних версиях С++. Во многих программах можно (и следует) избежать явного преобразования типов. В остальных – локализовать их в нескольких процедурах.

С++ унаследовал от С форму записи (T)e, означающую любое преобразование, которое может быть выражено комбинацией операций static_cast, reinterpret_cast и const_cast для получения значения типа Т из выражения е. Такой стиль намного опаснее, чем именованные операции преобразования, потому что приведенную форму записи сложнее отслеживать в большой программе и вид преобразования, который имел ввиду програмист, не очевиден. Ведь (Т)е может осуществлять и переносимое преобразование между близкими типами, и непереносимое преобразование между несвязанными типами, и, наконец, аннулировать действие модификатора const для указателя. Не зная конкретно типы Т и е, невозможно сказать, что делает (Т)е.










Последнее изменение этой страницы: 2018-04-12; просмотров: 376.

stydopedya.ru не претендует на авторское право материалов, которые вылажены, но предоставляет бесплатный доступ к ним. В случае нарушения авторского права или персональных данных напишите сюда...