#includeiostream #include string using namespace std; void String() { string s1("Hello"); string s2 = "World"; string s3 = s2; string s4(s2); cout s1 ' ' s2 " " s3 " " s4 endl; cout s1.length() endl; cout s1.empty() endl; for (int i = 0;i s
#include <string>
using namespace std;
void String()
{
string s1("Hello");
string s2 = "World";
string s3 = s2;
string s4(s2);
cout << s1 << ' ' << s2 << " " << s3 << " " << s4 << endl;
cout << s1.length() << endl;
cout << s1.empty() << endl;
for (int i = 0;i < s1.length();i++)
{
cout << s1.at(i) << endl;
}
cout << endl;
for (string::iterator index = s1.begin();index != s1.end();index++)
{
cout << *index << endl;
}
try {
cout << "使用at成员函数的数组方式,测试异常处理:" << endl;
for (unsigned int i = 0; i < s1.length() + 3; i++)
{
cout << s1.at(i) << "\t";//如果不使用at函数就会出现编译错误
}
cout << endl;
}
catch (...)
{
cout << "访问越界了" << endl;
}
cout << "------------------------" << endl;
string str1;
s1 = "abcdefg";
str1.assign(s1);//直接赋值
cout << str1 << endl;
str1.assign(s1, 1, 2);//复制子串
cout << str1 << endl;
str1.assign(s1, 1, str1.npos);//从位置1到末尾的子串进行赋值
cout << str1 << endl;
str1.assign(2, 'x');//重复2个x
cout << str1 << endl;
string::iterator itB = str1.begin();
string::iterator itE = str1.end();
str1.assign(itB, --itE);
cout << str1 << endl;
/*
abcdefg
bc
bcdefg
xx
x
*/
s1 = "abcdefg";
/*string->char* */
printf("%s\n", s1.c_str());
/*将string拷贝到char*指向的内存空间*/
char buf[128] = { 0 };
s1.copy(buf, 5, 0);
cout << "buf:" << buf << endl;
/*
abcdefg
buf:abcde
*/
s1 = "abc";
s2 = "ab";
cout << s1.compare(s2) << endl;
cout << s1 + s2 << endl;
cout << s1.append(s2) << endl;
cout << s1.substr(1, s1.npos) << endl;
cout << "------------------------" << endl;
s1 = "abcefg";
s2 = "hijklm";
s1.swap(s2);
cout << s1 << endl;
s1.replace(0, 1, s2);
cout << s1 << endl; //abcefgijklm
s1.replace(3, 1, 5, 'x');
cout << s1 << endl;//abcxxxxxfgijklm
string A("ello");
string B("H");
B.insert(1, A);
cout << B << endl;//Hello
A = "ello";
B = "H";
B.insert(1, "123456", 3);//H123
cout << B << endl;
A = "ello";
B = "H";
B.insert(1, A, 2, 2);
cout << B << endl;//Hlo
}