|
BDE 4.14.0 Production release
|
Provide functions that operate on IndexSpan and string objects.
IndexSpan and stringsThis component provides a struct, IndexSpanStringUtil, that serves as a namespace for utility functions that operate on IndexSpan and string objects. This component is designed to work on several representations of strings, including bsl::string, bsl::string_view, and it is also backwards compatible with bslstl::StringRef. Key operations of this utility include bind, for creating a bsl::string_view from an IndexSpan and a string, and the create methods that provide a way to create IndexSpan objects of a string object (of any kind) using positions defined by iterators and/or positions and/or length.
This section illustrates intended use of this component.
Suppose that we are creating a parser, and we want the results of the parsing to be stored in IndexSpan objects. The parser will have either a pointer (or "begin" iterator) into the original string input and then another pointer (or iterator) or a length to identify the end of the input. Turning the beginning and ending identifiers into an IndexSpan is a simple calculation, but one that is verbose and potentially error prone. Instead of implementing the calculation ourselves we use the convenience function create from IndexSpanStringUtil.
First, we define a string that we want to parse:
Then, we implement the parsing of the first name:
Next, we implement the parsing of the middle name, this time using length, rather than an end iterator (demonstrating an alternative create overload provided by IndexSpanStringUtil):
Then, we create the IndexSpan for the last name, using two positions:
Finally, we verify that the resulting IndexSpan objects correctly describe the parsed names of the full name:
Suppose that we have IndexSpan objects that define the first, middle, and last part of a string that has a full name in it and we want to get actual string views that correspond to those parts of the string. The bind functions of IndexSpanStringUtil provide that functionality. The bind functions return a bsl::string_view into the original string (so the characters of the string are not copied). Note that this example builds on Example 1.
First, we define a string view of the parsed string to show that bind works both on strings and string views:
Then we demonstrate binding IndexSpan object to that view:
Finally we demonstrate binding IndexSpan object to a bsl::string: