String object and its operations

Source: Internet
Author: User

Standard library type string

String of the standard library type indicates a variable length character sequence. The string type must first contain the string header file. As part of the standard library, string is defined in the namespace STD. The following example assumes that the following code is included:

# Include <string>

Using STD: string;

This section describes the most common string operations.

Define and initialize a String object

The class object initialization is determined by the class itself. A class can define many ways to initialize objects, but these methods must be different: the number of initial values is different, or the type of initial values is different.

String S1; // It is initialized by default. S1 is an empty string.

String S2 = S1; // S2 is a copy of S1.

String S3 = "hiya"; // S3 is a copy of the string's Literal Value

String S4 (10, 'C'); // The content of S4 is cccccccccccc

You can initialize a String object by default, so that an empty string is obtained, that is, there is no character to change the string object. If the literal value of a string is increased, all the characters except the last null character are copied to the created String object. If a number and a character are provided, the content of the string object is the sequence obtained after the given character is repeated several times consecutively.

How to initialize a String object in a table

String S1 is initialized by default, and S1 is an empty string

String S2 (S1) S2 is a copy of S1

String S2 = S1 is equivalent to S2 (S1). S2 is a copy of S1.

String S3 ("value") S3 is a copy of the nominal value "value", except for the last empty character of the nominal value

String S3 = "value" is equivalent to S3 ("value"). S3 is a copy of the nominal value "value ".

String S4 (n, 'C') initializes S4 as a string consisting of n consecutive characters C

Direct initialization and copy Initialization

The C ++ language has several different initialization methods. using string, we can clearly see the differences and connections between these initialization methods. If you useSymbol (=) initializes a variableActually, the execution isCopy InitializationThe compiler copies the initial values on the right of the equal sign to the newly created object. In contrast, if the equal sign is not usedDirect Initialization.

When there is only one initial value, you can use direct initialization or copy initialization. If there are multiple values used for initialization like S4 above, you can only initialize them directly.

String S5 = "hiya"; // copy Initialization

String S6 ("hiya"); // directly initialize

String S7 (10, 'C'); // directly Initialize. The content of S7 is cccccccccccc.

When multiple values are initialized, you must use the copy initialization method to process them. However, you need to explicitly create a (temporary) object for copying:

String S8 = string (10, 'C'); // copy initialization. The S8 content is cccccccccccc.

The initial value of S8 is string (10, 'C'). In fact, a string object is created using the numbers 10 and character C, then the string object is copied to s8. this statement is essentially equivalent to the following two-day sentence:

String temp (10, 'C'); // The content of temp is cccccccccccc

String S8 = temp; // copy temp to S8

In fact, although the statement for initializing S8 is valid, it is less readable than the method for initializing S7 and does not have any compensation advantages.

Operations on string objects

In addition to specifying how to initialize an object, a class also defines the operations that can be performed on the object. Among them, classes can define operations called by function names, just like the ISBN function of sales_item class, they can also define new meanings of operators such as <, +, and so on this class object.

String operation

OS <s writes S to the output stream OS and returns the OS

Is> S reads characters from is and assigns them to S,String separated by white space

Getline (is, S) reads a row from is and assigns it, and returns is

If S. Empty () S is null, true is returned; otherwise, false is returned.

S. Size () returns the number of characters in S.

S [N] returns the n-character reference of S. The position n starts from 0.

S1 + S2 returns the result after S1 and S2 are connected.

S1 = S2 replace the original characters in S1 with a copy of S2

S1! = S2 equality judgment is case sensitive to letters

<, <=,>,> = Compares character sequences in the dictionary and is case sensitive to letters.

Read and Write string objects

Use iostream to read and write int, double, and other built-in types of values. Yes. You can also use the IO operator to read and write string objects.

Cin input operation: During the read operation, the string object automatically ignores the white spaces (such as space characters, line breaks, and tabs) at the beginning and starts reading from the first real character, until the next blank is displayed. Only strings between two spaces can be read.

For example, if the input is "Hello World", only hello can be input, and no space is in the output result.

Similar to input and output operations of built-in types, such operations of string objects are the operation objects on the left of the return operator as their results. Therefore, multiple inputs or outputs can be written together:

String S1, S2;

Cin> S1> S2; // read the first input to S1, and the second input to S2.

Cout <S1 <S2 <Endl; // outputs two string objects

Assume that the above program is input with the same content "Hello World" as before, and the output will be "helloworld"

 

Use Getline to read a whole row

Sometimes we want to retain the white space in the final string. In this case, we should use the Getline function to replace the previous> operator. The parameter of the Getline function is an input stream and a string object. The function reads the content from the given input stream until it encounters a line break (note that the line break is also read ), then save the read content to the string object (note that the line break is not saved ). Getline only ends the read operation and returns the result when a line break is encountered, even if the line break is entered at the beginning. If the input is a linefeed, the result is a null string.

Like the input operator, Getline returns its stream parameters. Therefore, since the input operator can be used as a condition for judgment, we can also use the Getline result as a condition.

Note: The linefeed returned when the Getline function is triggered is actually discarded. The resulting string object does not contain this linefeed.

Empty and size operations of string

As the name suggests, the empty function returns a corresponding Boolean value based on whether the string object is null.

The size function returns the length of the string object (that is, the number of characters in the string object ).

 

String: size_type

For the size function, it seems reasonable to return an int or an unsigned value. In fact, the size function returns a string: size_type value.

The string class and most other standard library types define several ancillary types, which reflect the characteristics of the standard library type that are not related to the machine. The size_type is one of them.

Although we are not quite clear about the details of the size_type type, it is certain that it is an unsigned type value and is sufficient to store the size of any string object. All the size function return values used to store the string class should be of the size_type type.

In the past, size_type was a bit mysterious and difficult to understand and use. The new standard in C ++ 11 allows the compiler to deduce the type of a variable through auto or decltype:

Auto Len = line. Size (); // The LEN type is size_type

Since the size function returns an unsigned integer type, remember that if the expression contains both the signed and unsigned numbers, unexpected results may occur. For example, if n is an int with a negative value, the expression s. the result of size () <n is almost certainly true, because the negative value n is automatically converted into a comparison of the unsigned number.

 

Add two string objects

The two string objects are added together to get a new String object. The content is to concatenate the operation object on the left and the operation object on the right. That is to say, the result of using the addition operator for a String object is a new String object, which contains two characters: the first half is the characters contained in the string object on the left side of the plus sign, and the second half is the characters contained in the string object on the right side of the plus sign. In addition, the compound value assignment operator (+ =) is responsible for appending the content of the string object on the right to the end of the string object on the left:

String S1 = "hello,", S2 = "world \ n ";

String S3 = S1 + S2;

S1 + = S2;

 

String and string object addition

The standard library allows you to convert a String object to a string object, so you can replace the string object with the string object. Use this to rewrite the previous program into the following form:

String S1 = "hello", S2 = "world"

String S3 = S1 + "," + S2 + "\ n ";

When a String object is used in a statement, make sure that at least one of the computing objects on both sides of each addition operator (+) is a string;

String S4 = S1 + ","; // correct: adds a String object and a literal constant.

String S5 = "hello" + ","; // error: Neither operation object is a string

// Correct: each addition operator has a string object.

String S6 = S1 + "," + "world ";

String S7 = "hello" + "," + S2; // error: Neither operation object is a string

Where, string S6 = S1 + "," + "world" Neutron expression S1 + "," is a string object, which serves as the left operation object of the second addition operator at the same time, therefore, the preceding statement is equivalent to the following two statements:

String TMP = S1 + ",";

S6 = TMP + "world ";

On the other hand, the initialization of S7 is illegal, and the following form is formed after brackets are added according to its semantics:

String S7 = ("hello" + ",") + S2;

It is easy to see that the subexpression in the brackets tries to add the two character strings together, And the compiler cannot do this at all, so this statement is wrong.

Remember: The String Literal Value and string are different types.

 

Process characters in a string object

We often need to process characters in the string object separately. It is better to check whether a String object contains white space, change the letters in the string object to lowercase, or check whether a specific character appears.

The following is a function used to obtain and process a character.

Functions in the header file of cctype

Isalnum (c) is true when C is a letter or number

Isalpha (c) is true when C is a letter

Iscntrl (c) is true when C is a control character

Isdigit (c) is true when C is a number

Isgraph (c) is true when C is not a space but can be printed

Islower (c) is true when C is a lowercase letter

Isprint (c) is true when C is printable (that is, C is a space or C has a visual form)

Ispunch (c) is true when C is a punctuation mark (that is, C is not a control character, number, character, can print a blank)

Isspace (c) is true when C is blank (that is, C is a space, horizontal tab, vertical tab, carriage return, line feed, or paper feed)

Isupper (c) is true when C is an uppercase letter

Isxdigit (c) is true when C is a hexadecimal number

Tolower (C) If C is an upper-case letter, the corresponding lower-case letter is output: otherwise C is output as is

Toupper (C) If C is a lowercase letter, the corresponding uppercase letter is output: otherwise, C is output as is

Processing each character? Use a range-based for statement

If you want to perform some operations on each character in the string object, the best method is to use the for statement provided by the new C ++ 11 standard. This statement traverses each element of the given sequence and performs some operation on each value of the sequence. The syntax format is:

For (Declaration: expression)

Statement;

The expression part is an object used to represent a sequence, and the declaration part defines a variable, which will be used to access the basic elements in the sequence. During each iteration, the variables in the declaration part are initialized to the next element value in the expression part.

A String object represents the sequence of a character, so the string object can be used as the expression part of the range for statement.

Use the range for statement to change the characters in the string

To change the character value of a string object, you must define the cyclic variable as the reference type. Remember, a reference is just an alias for a given object, soWhen reference is used as a loop control variable, this variable is actually bound to each element of the sequence in sequence.. With this reference, we can change the characters it binds.

For example:

String S ("Hello world! ");

// Convert to a large write format

For (Auto & C: S)

C = toupper (c); // For each character in S (note that C is a reference)

Cout <S <Endl;

The above result will be:

Hello world !!!

During each iteration, variable C references the next character of String object S and assigns a value to C, that is, changing the value of the corresponding character in S. Therefore, when the following statement is executed:

C = toupper (c); // C is a reference, so the value assignment statement will change the character value in S.

Actually changed the value of the character bound to C. After the entire loop ends, all characters in STR are in uppercase.

 

Only processing part of characters?

The input parameter received by the subscript operator ([]) is a string: size_type value, which indicates the location of the character to be accessed:The returned result is a reference of the character at this position..

 

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.