现在的位置: 首页 > 综合 > 正文

用法区别总结

2014年09月05日 ⁄ 综合 ⁄ 共 9376字 ⁄ 字号 评论关闭

我相信很多人和我一样,在用到这三个头文件的时候总是稀里糊涂的,现总结如下,具体有什么疑问可查询MSDN。

总体来说:

<string.h>是旧的C 头文件,对应的是基于char*的字符串处理函数

<cstring>是对应于旧C 头文件的std 版本,主要用在MFC中;

<string>是包装了std 的C++头文件,是新的string 类,其分两种对应的是char和wchar_t,其对应的命名空间分别是using 
std::string;
using std::wstring;当然两者可以统一用 using
namespace std;

一句话:<string.h>和<cstring>基本没有分别;<string.h>和<string>是完全两个不同的头文件,只是像而已。

为了更好的使用<string.h>和<string>,下面看下这个头文件各包含哪些函数:

这是MSDN下的<string.h>的成员函数,具体可参见http://msdn.microsoft.com/en-us/library/tk97t156(v=vs.90).aspx

#if <TRADITIONAL C HEADERS> 
   #include <string.h> 
namespace std { 
   using ::memchr;  
   using ::memcmp; 
   using ::memcpy;  
   using ::memmove;  
   using ::memset; 
   using ::size_t;  
   using ::strcat;  
   using ::strchr;  
   using ::strcmp; 
   using ::strcoll;  
   using ::strcpy;  
   using ::strcspn; 
   using ::strerror; 
   using ::strlen; 
   using ::strncat; 
   using ::strncmp; 
   using ::strncpy;  
   using ::strpbrk; 
   using ::strrchr;  
   using ::strspn;  
   using ::strstr; 
   using ::strtok;  
   using ::strxfrm; 
} 
#endif

下面是<string>的成员函数,具体可参见http://msdn.microsoft.com/en-us/library/5zz6weyz(v=vs.71).aspx

Typedefs

allocator_type A type that represents the allocator class for a string object.
const_iterator A type that provides a random-access iterator that can access and read a const element in the string.
const_pointer A type that provides a pointer to a const element in a string.
const_reference A type that provides a reference to a const element stored in a string for reading and performing const operations.
const_reverse_iterator A type that provides a random-access iterator that can read any const element in the string.
difference_type A type that provides the difference between two iterators that refer to elements within the same string.
iterator A type that provides a random-access iterator that can read or modify any element in a string.
npos An unsigned integral value initialized to –1 that indicates either "not found" or "all remaining characters" when a search function fails.
pointer A type that provides a pointer to a character element in a string or character array.
reference A type that provides a reference to an element stored in a string.
reverse_iterator A type that provides a random-access iterator that can read or modify an element in a reversed string.
size_type An unsigned integral type for the number of elements in a string.
traits_type A type for the character traits of the elements stored in a string.
value_type A type that represents the type of characters stored in a string.

Member Functions

append Adds characters to the end of a string.
assign Assigns new character values to the contents of a string.
at Returns a reference to the element at a specified location in the string.
basic_string Constructs a string that is empty or initialized by specific characters or that is a copy of all or part of some other string object or C-string.
begin Returns an iterator addressing the first element in the string.
c_str Converts the contents of a string as a C-style, null-terminated, string.
capacity Returns the largest number of elements that could be stored in a string without increasing the memory allocation of the string.
clear Erases all elements of a string.
compare Compares a string with a specified string to determine if the two strings are equal or if one is lexicographically less than the other.
copy Copies at most a specified number of characters from an indexed position in a source string to a target character array.
data Converts the contents of a string into an array of characters.
empty Tests whether the string is contains characters or not.
end Returns an iterator that addresses the location succeeding the last element in a string.
erase Removes an element or a range of elements in a string from specified positions.
find Searches a string in a forward direction for the first occurrence of a substring that matches a specified sequence of characters.
find_first_not_of Searches through a string for the first character that is not any element of a specified string.
find_first_of Searches through a string for the first character that matches any element of a specified string.
find_last_not_of Searches through a string for the last character that is not any element of a specified string.
find_last_of Searches through a string for the last character that is an element of a specified string.
get_allocator Returns a copy of the allocator object used to construct the string.
insert Inserts an element or a number of elements or a range of elements into the string at a specified position.
length Returns the current number of elements in a string.
max_size Returns the maximum number of characters a string could contain.
push_back Adds an element to the end of the string.
rbegin Returns an iterator to the first element in a reversed string.
rend Returns an iterator that points just beyond the last element in a reversed string.
replace Replaces elements in a string at a specified position with specified characters or characters copied from other ranges or strings or C-strings.
reserve Sets the capacity of the string to a number at least as great as a specified number.
resize Specifies a new size for a string, appending or erasing elements as required.
rfind Searches a string in a backward direction for the first occurrence of a substring that matches a specified sequence of characters.
size Returns the current number of elements in a string.
substr Copies a substring of at most some number of characters from a string beginning from a specified position.
swap Exchange the contents of two strings.

Operators

operator+= Appends characters to a string.
operator= Assigns new character values to the contents of a string.
operator[] Provides a reference to the character with a specified index in a string.

综上,如果你想用strcat函数你就要添加<string.h>头文件,如果你想用到find函数你就要添加<string>的头文件了。

不过,相信你想这儿会想到CString类,它和上面提到的String类有什么区别呢?

CString是属于MFC的类,string类是属于标准c++库的,而且使用CString时要添加头文件"afx.h",不过通常添加“stdafx.h"即可。

CString中含有一些更加强大的功能,具体可看下http://msdn.microsoft.com/en-us/library/aa315043(v=vs.60).aspx#_mfc_construction_cstring

Construction

CString Constructs CString objects in various ways.


The String as an Array

GetLength Returns 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.
IsEmpty Tests whether a CString object contains no characters.
Empty Forces a string to have 0 length.
GetAt Returns the character at a given position.
operator [] Returns the character at a given position — operator substitution forGetAt.
SetAt Sets a character at a given position.
operator LPCTSTR Directly accesses characters stored in a CString object as a C-style string.


Assignment/Concatenation

operator = Assigns a new value to a CString object.
operator + Concatenates two strings and returns a new string.
operator += Concatenates a new string to the end of an existing string.


Comparison

operator == <, etc. Comparison operators (case sensitive).
Compare Compares two strings (case sensitive).
CompareNoCase Compares two strings (case insensitive).
Collate Compares two strings (case sensitive, uses locale-specific information).
CollateNoCase Compares two strings (case insensitive, uses locale-specific information).


Extraction

Mid Extracts the middle part of a string (like the Basic MID$ function).
Left Extracts the left part of a string (like the Basic LEFT$ function).
Right Extracts the right part of a string (like the Basic RIGHT$ function).
SpanIncluding Extracts a substring that contains only the characters in a set.
SpanExcluding Extracts a substring that contains only the characters not in a set.


Other Conversions

MakeUpper Converts all the characters in this string to uppercase characters.
MakeLower Converts all the characters in this string to lowercase characters.
MakeReverse Reverses the characters in this string.
Replace Replaces indicated characters with other characters.
Remove Removes indicated characters from a string.
Insert Inserts a single character or a substring at the given index within the string.
Delete Deletes a character or characters from a string.
Format Format the string as sprintf does.
FormatV Formats the string as vsprintf does.
TrimLeft Trim leading whitespace characters from the string.
TrimRight Trim trailing whitespace characters from the string.
FormatMessage Formats a message string.


Searching

Find Finds a character or substring inside a larger string.
ReverseFind Finds a character inside a larger string; starts from the end.
FindOneOf Finds the first matching character from a set.


Archive/Dump

operator << Inserts a CString object to an archive or dump context.
operator >> Extracts a CString object from an archive.


Buffer Access

GetBuffer Returns a pointer to the characters in the CString.
GetBufferSetLength Returns a pointer to the characters in the CString, truncating to the specified length.
ReleaseBuffer Releases control of the buffer returned by GetBuffer.
FreeExtra Removes any overhead of this string object by freeing any extra memory previously allocated to the string.
LockBuffer Disables reference counting and protects the string in the buffer.
UnlockBuffer Enables reference counting and releases the string in the buffer.


Windows-Specific

AllocSysString Allocates a BSTR from CString data.
SetSysString Sets an existing BSTR object with data from a CString object.
LoadString Loads an existing CString object from a Windows resource.
AnsiToOem Makes an in-place conversion from the ANSI character set to the OEM character set.
OemToAnsi Makes an in-place conversion from the OEM character set to the ANSI character set.

另外需要说明的是,CString类和String类通常需要相互转化来调用对应的函数:

1.CString和string的转化
stringstr="ksarea";
CStringcstr(str.c_str());//或者CString
cstr(str.data());初始化时才行

cstr=str.c_str();或者cstr=str.data();
str=cstr.GetBuffer(0)//CString
-> string

cstr.format("%s"str.c_str())//string->CString
cstr.format("%s"str.data())//string->CString
str = LPCSTR(cstr)//CString->string
/*c_str()和data()区别是:前者返回带'/0'的字符串,后者则返回不带'/0'的字符串*/
2.CString和int的转换
inti=123;
CStringstr;
str.format("%d",i);//int->CString 其他的基本类型转化类似
i=atoi(str);//CString->int 还有(atof,atol)
3.char*和CString的转换
CStringcstr="ksarea";
charptemp=cstr.getbuffer(0);
charstr;
strcpy(str,ptemp);//CString->char*
cstr.releasebuffer(-1);

char*str="lovesha";
CStringcstr=str;//char*->CString string类型不能直接赋值给CString

Reference:

http://www.cnblogs.com/xFreedom/archive/2011/05/16/2048037.html

http://msdn.microsoft.com/en-us/library/tk97t156(v=vs.90).aspx

http://msdn.microsoft.com/en-us/library/5zz6weyz(v=vs.71).aspx

http://blog.csdn.net/bitxinhai/article/details/2292014

http://msdn.microsoft.com/en-us/library/aa315043(v=vs.60).aspx#_mfc_construction_cstring

抱歉!评论已关闭.