Movatterモバイル変換


[0]ホーム

URL:




Chapter 5: The `string' Data Type

C++ offers many solutions for common problems. Most of these facilitiesare part of theStandard Template Library or they are implemented asgeneric algorithms (see chapter19).

Among the facilitiesC++ programmers have developed over and over againare those manipulating chunks of text, commonly calledstrings. TheCprogramming language offers rudimentary string support.

To process textC++ offers astd::string type. InC++the traditionalC library functions manipulating NTB strings aredeprecated in favor of usingstring objects. Many problems inCprograms are caused by buffer overruns, boundary errors and allocationproblems that can be traced back to improperly using these traditionalCstring library functions. Many of these problems can be prevented usingC++ string objects.

Actually,string objects areclass type variables, and in that sensethey are comparable to stream objects likecin andcout. In thissection the use ofstring type objects is covered. The focus is on theirdefinition and their use. When usingstring objects themember functionsyntax is commonly used:

        stringVariable.operation(argumentList)

For example, ifstring1 andstring2 are variables of typestd::string, then

        string1.compare(string2)

can be used to compare both strings.

In addition to the common member functions thestring class also offers awide variety ofoperators, like the assignment (=) and the comparisonoperator (==). Operators often result in code that is easy to understandand their use is generally preferred over the use of member functions offeringcomparable functionality. E.g., rather than writing

    if (string1.compare(string2) == 0)

the following is generally preferred:

    if (string1 == string2)

To define and usestring-type objects, sources must include the headerfile<string>. To merelydeclare the string typethe headeriosfwd can be included.

In addition tostd::string, the header filestring defines thefollowing string types:

5.1: Operations on strings

Some of the operations that can be performed on strings return indices withinthe strings. Whenever such an operation fails to find an appropriate index,thevaluestring::npos is returned. This value is a symbolicvalue of typestring::size_type, which is (for all practicalpurposes) an (unsigned)int.

Allstring member functions acceptingstring objects as arguments alsoaccept NTBS arguments. The same usually holds true for operators acceptingstring objects.

Somestring-members useiterators. Iterators are formally introducedin section18.2. Member functions using iterators are listed inthe next section (5.2), but the iterator concept itselfis not further covered by this chapter.

Strings support a large variety of members and operators. A short overviewlisting their capabilities is provided in this section, with subsequentsections offering a detailed discussion. The bottom line:C++ strings areextremely versatile and there is hardly a reason for falling back on theClibrary to process text.C++ strings handle all the required memorymanagement and thus memory related problems, which are the #1 source ofproblems inC programs, can be prevented whenC++ strings areused. Strings do come at a price, though. The class's extensive capabilitieshave also turned it into a beast. It's hard to learn and master all itsfeatures and in the end you'll find that not all that you expected is actuallythere. For example,std::string doesn't offer case-insensitivecomparisons. But in the end it isn't even as simple as that. Itis there,but it is somewhat hidden and at this point in theC++ Annotations it's tooearly to study into that hidden corner yet. Instead, realize thatC'sstandard librarydoes offer useful functions that can be used as long aswe're aware of their limitations and are able to avoid their traps. So fornow, to perform a traditionalcase-insensitive comparison of the contentof twostd::string objectsstr1 andstr2 the following will do:

    strcasecmp(str1.c_str(), str2.c_str());

Strings support the following functionality:

5.2: A std::string reference

In this section the string members and string-related operations arereferenced. The subsections cover, respectively the string's initializers,iterators, operators, and member functions. The following terminology is usedthroughout this section:

Bothopos andapos must refer to existing offsets, or an exception(cf. chapter10) is generated. In contrast,an andon mayexceed the number of available characters, in which case only the availablecharacters are considered.

Many members declare default values foron, an andapos. Some membersdeclare default values foropos. Default offset values are 0, the defaultvalues ofon andan isstring::npos, which can be interpreted as`the required number of characters to reach the end of the string'.

With members starting their operations at the end of the string object'scontent proceeding backwards, the default value ofopos is the index ofthe object'slast character, withon by default equal toopos + 1,representing the length of the substringending atopos.

In the overview of member functions presented below it may be assumed that allthese parameters accept default values unless indicated otherwise. Of course,the default argument values cannot be used if a function requires additionalarguments beyond the ones otherwise accepting default values.

Some members have overloaded versions expecting an initial argument of typechar const *. But even if that is not the case the first argument canalways be of typechar const * where a parameter ofstd::string isdefined.

Several member functions acceptiterators. Section18.2 coversthe technical aspects ofiterators, but these may be ignored at this pointwithout loss of continuity. Likeapos andopos, iterators must referto existing positions and/or to an existing range of characters within thestring object's content.

Allstring-member functions computing indices return thepredefined constantstring::npos on failure.

Thesliteral suffix to indicate that astd::string constant isintended when a string literal (like"hello world") is used. It can beused after declaringusing namespace std or, more specific, afterdeclaringusing namespace std::literals::string_literals.

When string literals are used when explicitly defining or usingstd::string objects thes-suffix is hardly ever required, but it maycome in handy when using theauto keyword. E.g.,auto str = "helloworld"s definesstd::string str, whereas it would have been acharconst * if the literal suffix had been omitted.

5.2.1: Initializers

After defining string objects they are guaranteed to be in a validstate. Atdefinition time string objects may be initialized in one of thefollowing ways: The followingstring constructors areavailable:

5.2.2: Iterators

See section18.2 for details aboutiterators. As a quickintroduction to iterators: an iterator acts like a pointer, and pointers canoften be used in situations where iterators are requested. Iterators usuallycome in pairs, defining a range of entities. The begin-iterator points to thefirst entity, the end-iterator points just beyond the last entity of therange. Their difference is equal to the number of entities in theiterator-range.

Iterators play an important role in the context ofgeneric algorithms(cf. chapter19). The classstd::string defines the followingiterator types:

5.2.3: Operators

String objects may be manipulated by member functions but also byoperators. Using operators often results in more natural-looking code. Incases where operators are available having equivalent functionality as memberfunction the operator is practically always preferred.

The following operators are available forstring objects (in the examples`object' and `argument' refer to existingstd::string objects).

5.2.4: Member functions

Thestd::string class offers many member function as well as additionalnon-member functions that should be considered part of the string class.All these functions are listed below in alphabetic order.

The symbolic valuestring::npos is defined by the string class. Itrepresents `index-not-found' when returned by member functions returningstring offset positions. Example: when calling `object.find('x')' (seebelow) on a string object not containing the character'x',nposis returned, as the requested position does not exist.

The final 0-byte used inC strings to indicate the end of an NTBS isnot considered part of aC++ string, and so the member function willreturnnpos, rather thanlength() when looking for 0 in a stringobject containing the characters of aC string.

Here are the standard functions that operate on objects of the classstring. When a parameter ofsize_t is mentioned it may be interpreted as aparameter of typestring::size_type, but without defining a defaultargument value. The typesize_type should be read asstring::size_type. Withsize_type the default argument valuesmentioned in section5.2 apply. All quoted functions aremember functions of the classstd::string, except where indicatedotherwise.

5.2.5: Conversion functions

Several string conversion functions are available operating on or producingstd::string objects. These functions are listed below in alphabeticorder. They are not member functions, but class-less (free) functions declaredin thestd namespace. The<string> header file must be includedbefore they can be used.

5.3: std::string_view

In addition to the classstd::string the classstd::string_view can beused as a wrapper-class ofchar arrays. The classstring_view canbe considered a light-weightstring class. Before usingstd::string_view objects the<string_view> header file must have beenincluded.

In addition to the standard constructors (default, copy, move) it offers thefollowing constructors:

Astring_view object does not contain its own copy of the initializeddata. Instead, it refers to the characters that were used when it wasinitially constructed. E.g., the following program produces unpredictableoutput, but when thehello array is defined as a static array it showshello:
    #include <string_view>    #include <iostream>    using namespace std;        string_view fun()    {        char hello[] = "hello";        return { hello };    }        int main()    {        string_view obj = fun();        cout << obj << '\n';    }

Thestd::string_view class provides the same members asstd::string,except for members extending thestring_view's characters (neitherappending nor inserting characters is possible). However,string_viewobjectscan modify their characters (using the index operator oratmember).

Thestring_view class also offers some extra members:

Likestd::string thestd::string_view class provides hashingfacilities, sostring_view objects can be used as keys in, e.g.,mapcontainers (cf. chapter12).




[8]ページ先頭

©2009-2025 Movatter.jp