String对象初始化最简单的形式
※创建空string对象,并不立即用字符数据对其初始化
※将一个文字的引用字符数组作为参数传递给构造函数,以此来对一个string对象进行初始化。
※用等号(=)来初始化一个string对象。
※用一个string对象初始化另一个string对象
例:
//: C03:SmallString.cpp
#include <string>
using namespace std;
int main() {
string imBlank;
string heyMom("where are my socks?");
string standardReply="Beamed into deep"
"space on wide angle dispersion?";
string useThisOneAgain(standardReply);
} ///:~
String对象的进一步操作
※使用C语言的char型数组或C++string类两者任一个的一部分。
※用operator+来将不同的初始化数据源结合在一起。
※用string对象的成员函数substr()来创建一个子串。
例:
//:C03:SmallString2.cpp
#include <string>
#include <iostream>
using namespace std;
int main()
{
string s1("What is the sound of one clam napping?");
string s2("Anything worth doing is worth overdoing.");
string s3("I saw Elivis in a UFO");
//copy the first 8 chars;
string s4(s1,0,8);
cout<<s4<<endl;
//copy 6 chars from the middle of the source:
string s5(s2,15,6);
cout<<s6<<endl;
//copy from middle to end:
string s6(s3,6,15);
cout<<s6<<endl;
//copy many different things:
string quoteme=s4+"that"+
//substr()copies 10 chars at element 20
s1.substr(20,10)+s5+
//substr() copies up to either 100 char
// or eos starting at element 5
"with"+s3.substr(5,100)++
//ok to copy a single char this way
s1.substr(37,1);
cout<<quoteme<<endl;
} ///:~
运行结果:
what is
doing
Elvis in a UFO
what is that one clam doing with Elvis in a UFO?
另一个稍微精巧些的初始化方法
利用string类的迭代器string::begin()和string::end().
使用迭代器来指示字符序列的开始和结尾。可以给string类的构造函数传递两个迭代器,构造函数从一个迭代器开始直到另一个迭代器结束,将它们的数据拷贝到新的string对象中。
例:
//:C03:StringIterators.cpp
#include <string>
#include <iostream>
#include <cassert>
using namespace std;
int main() {
string source("xxx");
string s(source.begin(),source.end());
assert(s==source);
} ///:~
注意:不可以使用单个字符、ASCII码或其他整数值来初始化C++字符串。
可用单个字符的多个拷贝来初始化字符串:
//:C03:UhOh.cpp
#include <string>
#include <cassert>
using namespace std;
int main(){
//Error: no single char inits
//!string nothingDoing1('a');
//Error: no integer inits
//!string nothingDoing2(0x37);
//The following is legal:
string okay(5,'a');
assert(okay==string("aaaaa"));
}///:~