beautypg.com

String comparisons, Searching operations, Copy and substring – HP Integrity NonStop H-Series User Manual

Page 135

background image

Copy and Substring

The member function copy() generates a substring of the receiver, then assigns this substring to the
target given as the first argument. The range of values for the substring is specified either by an
initial position, or a position and a length.

s3.copy (s4, 2); // assign to s4 positions 2 to end of s3
s5.copy (s4, 2, 3); // assign to s4 positions 2 to 4 of s5

The member function substr() returns a string that represents a portion of the current string. The
range is specified by either an initial position, or a position and a length.

cout << s4.substr(3) << endl; // output 3 to end
cout << s4.substr(3, 2) << endl; // output positions 3 and 4

String Comparisons

Comparing Strings

The member function compare() is used to perform a lexical comparison between the receiver and
an argument string. Optional arguments permit the specification of a different starting position or a
starting position and length of the argument string. See

Chapter 13 (

Lexical Comparison

)

for a

description of lexical ordering. The function returns a negative value if the receiver is
lexicographically smaller than the argument, a zero value if they are equal and a positive value if
the receiver is larger than the argument.

The relational and equality operators (<, <=, ==, !=, >= and >) are all defined using the comparison
member function. Comparisons can be made either between two strings, or between strings and
ordinary C-style character literals.

Searching Operations

The member function find() determines the first occurrence of the argument string in the current
string. An optional integer argument lets you specify the starting position for the search.
(Remember that string index positions begin at zero.) If the function can locate such a match, it
returns the starting index of the match in the current string. Otherwise, it returns a value out of the
range of the set of legal subscripts for the string. The function rfind() is similar, but scans the string
from the end, moving backwards.

s1 = "mississippi";
cout << s1.find("ss") << endl; // returns 2
cout << s1.find("ss", 3) << endl; // returns 5
cout << s1.rfind("ss") << endl; // returns 5
cout << s1.rfind("ss", 4) << endl; // returns 2

The functions find_first_of(), find_last_of(), find_first_not_of(), and find_last_not_of() treat the
argument string as a set of characters. As with many of the other functions, one or two optional
integer arguments can be used to specify a subset of the current string. These functions find the first
(or last) character that is either present (or absent) from the argument set. The position of the given

This manual is related to the following products: