C ++ string class
The C ++ standard template library (STL) contains a string class that is used in several computer science classes. In order to use the string class you shoshould include the following statements:
# Include <string>
Using STD: string;
The following examples assume these declarations and initial values for each:
String S = "ABC def ABC ";
String S2 = "ABCDE uvwxyz ";
Char C;
Char ch [] = "ABA Daba do ";
Char * CP = CH;
Unsigned int I;
| Stream Input |
Cin> S; |
Changes the value of S to the value read in. The value stops at whitespace. |
| Stream output |
Cout <s; |
Writes the string to the specified output stream. |
| Line Input |
Getline (CIN, S ); |
Reads everything up to the next newline character and puts the result into the specified string variable. |
| Assignment |
S = S2; S = "ABC "; S = CH; S = CP; |
A string literal or a string variable or a character array can be assigned to a string variable. The last two assignments have the same effect. |
| Subscript |
S [1] = 'C '; C = s [1]; |
Changes s to equal "ACC def ABC" Sets C to 'B'. The subscript operator returns a char value, not a string value. |
| Length |
I = S. Length (); I = S. Size (); |
Either example sets I to the current length of the string s |
| Empty? |
If (S. Empty () I ++; If (S == "") I ++; |
Both examples Add 1 to I if string S is now empty |
| Relational operators |
If (S <S2) I ++; |
Uses ASCII code to determine which string is smaller. Here the condition is true because a space comes before letter d |
| Concatenation |
S2 = S2 + "X "; S2 + = "X "; |
Both examples add X to the end of S2 |
| Substring |
S = s2.substr (1, 4 ); S = s2.substr (1, 50 ); |
The first example starts in position 1 of S2 and takes 4 characters, setting s to "bcde ". in the second example, S is set to "bcde uvwxyz ". if the length specified is longer than the remaining number of characters, the rest of the string is used. the first position in a string is position 0. |
| Substring replace |
S. Replace (4,3, "x "); |
Replaces the three characters of s beginning in position 4 with the character X. Variable S is set to "ABC x ABC ". |
| Substring Removal |
S. Erase (4, 5 ); S. Erase (4 ); |
Removes the five characters starting in position 4 of S. The new value of S is "abc bc ". Remove from position 4 to end of string. The new value of S is "ABC ". |
| Character array to string |
S = CH; |
Converts character array ch into string S. |
| String to character array |
CP = S. c_str (); |
Pointer CP points to a character array with the same characters as S. |
| Pattern Matching |
I = S. Find ("AB", 4 ); If (S. rfind ("AB", 4 )! = String: NPOs) Cout <"yes" <Endl; |
The first example returns the position of the substring "AB" starting the search in position 4. sets I to 8. The find and rfind functions return the unsigned intString: NPOsIf substring not found. The second example searches from right to left starting at position 4. Since the substring is found, the word yes is printed. |