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