1,Initialize
Examples for explaining
1),std::string myStr("This is my first passage in C++ blog."); string myStr="This is my first passage in C++ blog.//using nameplace std;
2),std::string myStr1(myStr);
3),const char* c_styleCh("This is a c_style string,I can also let it initialized for me!"); std::string myStr(c_styleCh);
4),Partial initialization.
string parIniString(myStr,5);
5)Initialize a string object to contain 10 'a's
string strRepeatChars(10,'a');
2,visit contents
1),using iterators
int m=0;
string::const_iterator i;
for(i=STLStr.begin ();i!=STLStr.end ();i++)
{
cout<<"Character["<<m++<<"] is: ";
cout<<*i<<endl;
}
2)using array syntax '[]'
for(size_t n=0;n<STLStr.length ();n++)
{
cout<<"STLStr["<<n<<"]";
cout<<STLStr[n]<<endl;
}
3,append strings
1) using '+='
~ sth (to sth) (formal) to add sth to the end of a piece of writing
2)using "append()" function
1>append string objects
string str3="I forgive all my faults!";
str1.append(str3);
cout<<str1<<endl<<endl;
2>append s_style strings
const char* str4("Science truth;I'm reaching it!");
str1.append(str4);
cout<<str1<<endl<<endl;
4,using "find()" function to find a substring
1)find the location where the substring appears the first time
size_t nOffset=myStr.find("learning",0);
if(nOffset!=string::npos )
cout<<"First: "<<nOffset;
2)find all locations of the substring
size_t nSubstringOffset=myStr.find ("learning",0);
while(nSubstringOffset!=string::npos )
{
cout<<"\"learning\" found at offset: "<<nSubstringOffset<<endl;
size_t nSearchOffset=nSubstringOffset+1;
nSubstringOffset=myStr.find ("learning",nSearchOffset);
}
5,"erase()" function
1)myStr.erase(41,50);//41,50 are the locations of the elements in the string.
2) erase a certain letter from the string.
#include<algorithm>
string::iterator i=find(myStr.begin (),myStr.end (),'i');
if(i!=myStr.end ())
myStr.erase (i);//Only first 'i' is deleted!
6, transform: toupper / tolower
#include<algorithm>
string myStr;
cout<<"Input a string to transform:"<<endl<<"<";
getline(cin,myStr);
cout<<endl;
transform(myStr.begin(),myStr.end (),myStr.begin (),toupper);
7, reverse an string
#include<algorithm>
string myStr("Reverse myStr! Haha!");
reverse(myStr.begin (),myStr.end ());
8,'+' means append two strings and return the result.
string strRes=str1+" "+str2" ";
%Words
#append ~ sth (to sth) (formal) to add sth to the end of a piece of writing
*References:
1,Jesse Liberty, "Sam Teaches Youself C++ in One Hour a Day"(M)