// fig19_01.cpp
// demonstrating string assignment and concatenation
#include <iostream>
#include <string> // 完全不同于string.h 可以include文件下找到
//#include <string.h>
// 应注意string.h 中字符处理函数的区别
using namespace std; // 采取标准命名空间 iostream 不同于 iostream.h
// 全部函数可以在basic_string中查找 MSDN
int main()
{
string s1( "cat" ), s2, s3;
s2 = s1;
s3.assign( s1 );
cout<< "s1:" << s1 << "\ns2:" << s2 << "\ns3:" << s3 << endl;
// modify s2 and s3
s2[0] = s3[2] = 'r';
cout<< "After modification of s2 and s3:\n"
<< "s1:" << s1 << "\ns2:" << s2 << "\ns3:" << s3 << endl;
// demostrating member function at()
int len = s3.length();
for( int x=0; x<len; ++x )
cout<< s3.at( x );
// concatenation
string s4( s1 + "apult" ), s5;
//overloaded +=
s3 += "pet";
s1.append( "acomb" );
s5.append( s1, 4, s1.size() );
cout<< "\n After concatcenation:\n"
<< "s1:" << s1 << "\ns2:" << s2 << "\ns3:" << s3
<< "\ns4:" << s4 << "\ns5:" << s5 <<endl;
////////// 子串分析 ///////////////
string s6( " The airplane flew away." );
cout<< s6.substr( 7,5 ) << endl; // 从第7个开始读取5个
// ********* 交换 ************ //
string first( "one" ), second( "two" );
cout<< "Before swap:\n first: " << first
<< "\n second: " << second << endl;
first.swap( second );
cout<< "After swap:\n first: " << first
<< "\n second: " << second << endl;
// length or size 表示目前string 的大小或长度,是目前存放的字符数
// capacity 是不必增加内存即可存放的总的元素个数
// max_size 是最多能放多少
// find( "subtree" ) 是从头开始找subtree,找到返回下标
// rfind 为从后往回找
// find_first_ of 第一次找到
// find_last_of
// find_fist_not_of( "abcd" ) 打到第一个不在"abcd"中的字符的下标,从头找
// find_last_not_of 从尾找
// replace insert compare参见 basic_string
// < > = >= <= != 等都有重载,参见basic_string
return 0;
}
转载于:https://my.oschina.net/delmore/blog/4777