C++string处理,借助operator+和operator+=可以如此轻而易举地实现
string的合并与追加
运算符使合并串的操作在语法上类似于数值型数据的加法运算
//: C03:AddStrings.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
#include <string>
#include <cassert>
using namespace std;
int main() {
string s1("This ");
// s1 "This " std::basic_string<char,std::char_traits<char>,std::allocator<char> >
string s2("That ");
// s2 "That " std::basic_string<char,std::char_traits<char>,std::allocator<char> >
string s3("The other ");
// s3 "The other " std::basic_string<char,std::char_traits<char>,std::allocator<char> >
// operator+ concatenates strings
s1 = s1 + s2;
// s1 "This That " std::basic_string<char,std::char_traits<char>,std::allocator<char> >
assert(s1 == "This That ");
// 返回 std::operator==<char,std::char_traits<char>,std::allocator<char> > true bool
// Another way to concatenates strings
s1 += s3;
// s1 "This That The other " std::basic_string<char,std::char_traits<char>,std::allocator<char> >
assert(s1 == "This That The other ");
// s1 "This That The other " std::basic_string<char,std::char_traits<char>,std::allocator<char> >
// You can index the string on the right
s1 += s3 + s3[4] + "ooh lala";
// s1 "This That The other The other oooh lala" std::basic_string<char,std::char_traits<char>,std::allocator<char> >
assert(s1 == "This That The other The other oooh lala");
// 返回 std::operator==<char,std::char_traits<char>,std::allocator<char> > true bool
} ///:~
没有弹出异常对话框,说明正确运行
operator+和operator+=运算符是合并string数据的一种即灵活又
方便的方法。
在语句的右边,程序员几乎可以采用任意一种样式对由单字符或多字符
构成的分组进行赋值