<cstring>、<string.h>和<string>用法区别总结

来源:互联网 发布:刘吉桦陈铭 知乎 编辑:程序博客网 时间:2024/05/20 05:10

我相信很多人和我一样,在用到这三个头文件的时候总是稀里糊涂的,现总结如下,具体有什么疑问可查询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_typeA type that represents the allocator class for a string object.const_iteratorA type that provides a random-access iterator that can access and read a const element in the string.const_pointerA type that provides a pointer to a const element in a string.const_referenceA type that provides a reference to a const element stored in a string for reading and performing const operations.const_reverse_iteratorA type that provides a random-access iterator that can read any const element in the string.difference_typeA type that provides the difference between two iterators that refer to elements within the same string.iteratorA type that provides a random-access iterator that can read or modify any element in a string.nposAn unsigned integral value initialized to –1 that indicates either "not found" or "all remaining characters" when a search function fails.pointerA type that provides a pointer to a character element in a string or character array.referenceA type that provides a reference to an element stored in a string.reverse_iteratorA type that provides a random-access iterator that can read or modify an element in a reversed string.size_typeAn unsigned integral type for the number of elements in a string.traits_typeA type for the character traits of the elements stored in a string.value_typeA type that represents the type of characters stored in a string.

Member Functions

appendAdds characters to the end of a string.assignAssigns new character values to the contents of a string.atReturns a reference to the element at a specified location in the string.basic_stringConstructs 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.beginReturns an iterator addressing the first element in the string.c_strConverts the contents of a string as a C-style, null-terminated, string.capacityReturns the largest number of elements that could be stored in a string without increasing the memory allocation of the string.clearErases all elements of a string.compareCompares a string with a specified string to determine if the two strings are equal or if one is lexicographically less than the other.copyCopies at most a specified number of characters from an indexed position in a source string to a target character array.dataConverts the contents of a string into an array of characters.emptyTests whether the string is contains characters or not.endReturns an iterator that addresses the location succeeding the last element in a string.eraseRemoves an element or a range of elements in a string from specified positions.findSearches a string in a forward direction for the first occurrence of a substring that matches a specified sequence of characters.find_first_not_ofSearches through a string for the first character that is not any element of a specified string.find_first_ofSearches through a string for the first character that matches any element of a specified string.find_last_not_ofSearches through a string for the last character that is not any element of a specified string.find_last_ofSearches through a string for the last character that is an element of a specified string.get_allocatorReturns a copy of the allocator object used to construct the string.insertInserts an element or a number of elements or a range of elements into the string at a specified position.lengthReturns the current number of elements in a string.max_sizeReturns the maximum number of characters a string could contain.push_backAdds an element to the end of the string.rbeginReturns an iterator to the first element in a reversed string.rendReturns an iterator that points just beyond the last element in a reversed string.replaceReplaces elements in a string at a specified position with specified characters or characters copied from other ranges or strings or C-strings.reserveSets the capacity of the string to a number at least as great as a specified number.resizeSpecifies a new size for a string, appending or erasing elements as required.rfindSearches a string in a backward direction for the first occurrence of a substring that matches a specified sequence of characters.sizeReturns the current number of elements in a string.substrCopies a substring of at most some number of characters from a string beginning from a specified position.swapExchange 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

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.IsEmptyTests whether a CString object contains no characters.EmptyForces a string to have 0 length.GetAtReturns the character at a given position.operator []Returns the character at a given position — operator substitution forGetAt.SetAtSets a character at a given position.operator LPCTSTRDirectly 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).CompareCompares two strings (case sensitive).CompareNoCaseCompares two strings (case insensitive).CollateCompares two strings (case sensitive, uses locale-specific information).CollateNoCaseCompares two strings (case insensitive, uses locale-specific information).

Extraction

MidExtracts the middle part of a string (like the Basic MID$ function).LeftExtracts the left part of a string (like the Basic LEFT$ function).RightExtracts the right part of a string (like the Basic RIGHT$ function).SpanIncludingExtracts a substring that contains only the characters in a set.SpanExcludingExtracts a substring that contains only the characters not in a set.

Other Conversions

MakeUpperConverts all the characters in this string to uppercase characters.MakeLowerConverts all the characters in this string to lowercase characters.MakeReverseReverses the characters in this string.ReplaceReplaces indicated characters with other characters.RemoveRemoves indicated characters from a string.InsertInserts a single character or a substring at the given index within the string.DeleteDeletes a character or characters from a string.FormatFormat the string as sprintf does.FormatVFormats the string as vsprintf does.TrimLeftTrim leading whitespace characters from the string.TrimRightTrim trailing whitespace characters from the string.FormatMessageFormats a message string.

Searching

FindFinds a character or substring inside a larger string.ReverseFindFinds a character inside a larger string; starts from the end.FindOneOfFinds 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

GetBufferReturns a pointer to the characters in the CString.GetBufferSetLengthReturns a pointer to the characters in the CString, truncating to the specified length.ReleaseBufferReleases control of the buffer returned by GetBuffer.FreeExtraRemoves any overhead of this string object by freeing any extra memory previously allocated to the string.LockBufferDisables reference counting and protects the string in the buffer.UnlockBufferEnables reference counting and releases the string in the buffer.

Windows-Specific

AllocSysStringAllocates a BSTR from CString data.SetSysStringSets an existing BSTR object with data from a CString object.LoadStringLoads an existing CString object from a Windows resource.AnsiToOemMakes an in-place conversion from the ANSI character set to the OEM character set.OemToAnsiMakes 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


原创粉丝点击