Getting information about a string

The max_size method will give the maximum size of the string of the specified character type on your computer architecture and this can be surprisingly large. For example, on a 64-bit Windows computer with 2 GB of memory, max_size for a string object will return 4 billion characters, and for a wstring object the method will return 2 billion characters. This is clearly more than the memory in the machine! The other size methods return more meaningful values. The length method returns the same value as the size method, that is, how many items (characters) there are in the string. The capacity method indicates how much memory is already allocated for the string in terms of the number of characters.

You can compare a string with another by calling its compare method. This returns an int and not a bool (but note that an int can be converted silently to a bool), where a return value of 0 means that the two strings are the same. If they are not the same, this method returns a negative value if the parameter string is greater that the operand string, or a positive value if the parameter is less than the operand string. In this respect greater and less than will test the ordering of the strings alphabetically. In addition, there are global operators defined for <, <=, ==, >=, and > to compare string objects.

A string object can be used like a C string through the c_str method. The pointer returned is const; you should be aware that the pointer may be invalidated if the string object is changed, so you should not store this pointer. You should not use &str[0] to get a C string pointer for the C++ string str because the internal buffer used by the string classes is not guaranteed to be NUL terminated. The c_str method is provided to return a pointer that can be used as a C string, and hence NUL terminated.

If you want to copy data from the C++ string to a C buffer you can call the copy method. You pass the destination pointer and the number of characters to copy as parameters (and optionally an offset) and the method will attempt to copy, at most, the specified number of characters to the destination buffer: but without a null termination character. This method assumes that the destination buffer is big enough to hold the copied characters (and you should take steps to ensure this). If you want to pass the size of the buffer so that the method performs this check for you, call the _Copy_s method instead.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset