C + + learning the access and stitching of the PNS string string

Source: Internet
Author: User

accessing characters in a string

String strings can also be used to access each of these characters in the same way as a string array. The starting subscript for string strings is still starting at 0. Take a look at the following code:

#include <iostream>#include<string>using namespacestd;intMain () {stringS1; S1="1234567890";  for(intI=0, Len=s1.length (); i<len; i++) cout<<s1[i]<<" "; cout<<Endl; s1[5] ='5'; cout<<s1<<Endl; return 0;}

In this example, a string variable S1 is defined and assigned a value of "1234567890", followed by A for loop to iterate through the output of each character. With the subscript, in addition to the ability to access each character, you can also modify each character, the s1[5] = ‘5‘; statement will change the 6th character to ' 5 ', so S1 finally "1234557890".

Concatenation of strings

With the string class, we can use the "+" or "+ =" operators to directly stitch strings, it is very convenient, no longer need to use the C language strcat (), strcpy (), malloc () and other functions to splice strings, no longer have to worry about the space is not enough to overflow.

When you use "+" to stitch a string, either side of the operator can be a string string, a string string and a C-style string, or a string string and a char character. Take a look at the following example:

#include <iostream>#include<string>using namespacestd;intMain () {stringS1, S2, S3; S1=" First"; S2="Second"; S3= S1 +S2; cout<< S3 <<Endl; S2+=S1; cout<< S2 <<Endl; S1+="Third"; cout<< S1 <<Endl; S1+='a'; cout<< S1 <<Endl; return 0;}

C + + learning the access and stitching of the PNS string string

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.