C++string class __c++

Source: Internet
Author: User

String class in a string header file, string is defined in a namespace STD, and if you want to use a string, you must include the following code at the beginning:

#include <string>
using std::string;
defining and initializing a String object

There are several ways:

string S1;                  Default initialization, S1 is an empty string
string s2 (S1);              S2 is a copy of the S1
string s2 = S1;             Same as on the same
string S3 ("value");         S3 is a copy of the literal "value", except for the last null character, all characters are copied to the newly created string object to
string s3 = "value";        Same as on the same
string S4 (N, ' C ');          Initializes the S4 to a string with a continuous n-character C

Visible from above, there are two initialization methods, copy initialization and direct initialization. Initializing a variable with an equal sign (=) actually performs a copy initialization, and the compiler copies the initial value on the right side of the equal sign to the newly created object. Instead of using an equal sign, the line is directly initialized. When you initialize with more than one value, you are initializing directly, or you can use copy initialization in the following ways:

String S5 = String (ten, ' C ');

is essentially equivalent to initializing in the following ways:

The string temp = string (' C ');
string S5 = temp;
operations on a string object Input and Output
OS << s                     //writes s to the output stream, returns the OS is >> S//To
read the                     string from is, and the string is delimited by whitespace, and returns is
Getline (is, s)              // Reads a row from is to S, returns the IS

When a read operation is performed, the string object automatically ignores the opening blanks (spaces, line breaks, tabs, and so on) and reads from the first real character until the next blank is encountered.
Like an input-output operation of a built-in type, this type of operation for a string object is also the result of the Operation object on the left side of the return operator. As a result, multiple inputs and multiple outputs can be linked together.
If you want white space characters to be retained in the resulting string, you should use the Getline function instead of the original >> operator. The parameter of the Getline function is an input stream and a string object. Function reads content from a given stream until it encounters a newline character (the newline character is also read in), and then saves the read to a String object (no line breaks, which are actually discarded). The Getline function ends the read operation as soon as it encounters a newline character and returns the result, even if the first line is a newline character, and if that happens, the result is an empty string. The Getline function also returns its flow parameters, which can be used as a criterion.
The following procedures are available:

#include <iostream>
#include <string>
using std::string;
Using Std::cout;
Using Std::cin;
Using Std::endl;
int main (int argc, char const *argv[])
{
    string line = ' Hello ';
    while (Getline (CIN, line))
        cout << line << Endl;

The Getline function empties the contents of the original string object and stores the read string into a string object.
Ends the loop when Getline reads the end tag of the file. The way to enter a file close tag under Windows is to Ctrl+z and return. The test found that the function terminates only at the beginning of the entry as Ctrl+z, and if the location does not begin, the program does not terminate. and ignores the content behind the ctrl+z, and presses two times to enter only then will print the string content on the screen, Ctrl+z displays as garbled. empty and size operations for string

The empty function returns a Boolean value based on whether the string object is empty, returns true if it is empty, and does not return FALSE for null. Use the following:

string line;
if (line.empty) {
...
}

The size function returns the length of a string object, that is, the number of characters in a string object. Its return value is a value of type String::size_type, defined in class string, and is a value of an unsigned type. In the c++11 new standard, the compiler is allowed to infer the type of a variable by either auto or Decltype. So you can have:

String line = "Hello";
Auto size = Line.size ();

You don't need to know the details of the String::size_type type.
Because the size function returns an unsigned integer, it can have unpredictable consequences if you mix signed and unsigned numbers in an expression. If n is a negative int, the expression s.size () is compared

Equality operator (= = and. =) can verify that two string objects are equal or not equal.
Relational operators (<=, >=) detect the size relationships of two string objects, respectively. These operators are in dictionary order, and their rules are as follows:
1. If two string objects are not of equal length and each character of the shorter string object is the same as the character at the corresponding position of the longer string object, the shorter object is less than the longer object.
2. If two string objects are inconsistent in some places, the result of a string object comparison is actually the result of the first pair of different characters in the two string object.

string str = "Hello";
string phrase = "Hello world";
String slang = "Hiya";

Object STR is less than object phrase, and object slang is larger than str and phrase. Add

Two string objects are added to get a new string object that is connected to the left-hand operator object and to the right-hand operator object.
Because the standard library allows character literals and string literals to be converted to string objects, you can also use character literal values or string literals to add to a string object. When you mix string objects and character literals and string literals into one statement, you must ensure that at least one of the objects on both sides of each addition operator is of type string to facilitate type conversions:

string S1 = "Hello";
String s2 = S1 + ", world" + ' \ n ';                  Correctly, a string object is added to a string literal value and a character literals
s3 = "Hello" + ",";             Error, two string literals cannot be added
string s4 = S1 + "," + "world";        correctly, each addition operator has an object that is string
string s5 = "Hello" + "," + S1;    Error, cannot add literal value directly

The S4 initialization process can be grouped as follows:

String S4 = (S1 + ",") + "world";

This is equivalent to the following procedure:

String temp = S1 + ",";
String S4 = temp + "World";

The S5 initialization process is illegal, and its equivalence process is as follows:

String S5 = ("Hello" + ",") + S1;

The literal value cannot be added directly.
For some historical reasons, and also for C compatibility, the type of string literals in C + + is not an object of the standard library type string. String literals are different types of strings. accessing characters on a string object based on scope for statement

The scope based for statement syntax form is:

for (declaration:expression)
    statement

Expression is an object that represents a sequence. The declaration section is responsible for defining a variable that will be used to access the underlying element in the sequence. Each iteration, the declaration portion of the variable is initialized to the value of the next element in the expression section.
Such as:

String str ("Hello World");
for (auto c:str) {
    cout << c << endl;
}

By using the Auto keyword to let the compiler determine the type of variable C, this is char.
You can change the value of a character in a string object by declaring a variable of auto definition as a reference type. Such as:

string str = "Hello world";
for (auto &c:str) {
    toupper (c);
}

About the Auto keyword see C++11auto part of the content. ToUpper is a function in the Cctype library. The C + + standard library is compatible with the standard library in the language of "H", and removing the original. * S. h before adding C to indicate that it is a header file belonging to the C language standard library. The Cctype header file is the same as the Ctype.h header file content. Use subscript

The input parameter received by the subscript operator ([]) is the value of the String::size_type type, representing the position of the character to be accessed, which returns a reference to the character at that position. When a string's subscript starts at 0 to size ()-1, attempting to use a subscript that exceeds this range throws unpredictable consequences, as is the use of subscript access to an empty string object. Use the subscript to perform the iteration as follows:

string str = "Hello world";
For (Decltype (Str.size ()) index = 0; index!= str.size (); index++)
    cout << Str[index] << Endl;

The C + + standard does not require the standard library to detect whether subscript is legal. Once a subscript is used that is out of range, unpredictable results are produced. iterator-based access

See the iterator section for details.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.