string初始化,有三种方法:s1[i],迭代器,s1.at(i)抛出异常分别如下:
void main2()
{
string s1 = "abcdefg";
for (int i = 0; i < s1.length(); i++)
{
cout << s1[i] << " ";
}
for (string::iterator it = s1.begin(); it != s1.end(); it++)
{
cout << *it << endl;
}
for (int i = 0; i < s1.length(); i++)
{
cout << s1.at(i) << endl;
}
try
{
for (int i = 0; i < s1.length() + 3; i++)
{
cout << s1.at(i) << " "; //抛出异常
}
}
catch (...)
{
cout << "发生异常\n";
}
}
输出结果:
a b c d e f g a
b
c
d
e
f
g
a
b
c
d
e
f
g
a b c d e f g 发生异常
请按任意键继续. . .
字符串连接
//连接字符串
void main4()
{
string s1 = "aaa";
string s2 = "bbb";
s1 = s1 + s2;
cout << s1 << endl;
string s3 = "aaa";
string s4 = "bbb";
s3.append(s4);
cout << s3 << endl;
}
输出结果:
aaabbb
aaabbb
请按任意键继续. . .
字符串的查找和替换
// 字符串查找和替换
void main5()
{
string s1 = “there is there that the real danger is not that the computer”;
int index = s1.find(“there”, 0); //这个函数记录第一次出现的数组下标。
cout << “index” << index << endl;
//输出结果0。
int offindex = s1.find(“there”, 0);
while (offindex != string::npos)
{
cout << “offindex” << offindex << endl;
s1.replace(offindex, 3, “thg”); //这行代码是要替换的thg,
offindex = offindex + 1;
offindex = s1.find(“there”, offindex);
}
//替换
cout << s1 << endl;
}
//截断与删除
void main6()
{
string s1 = “there is there that the real danger is not that the computer”;
int index = s1.find(“there”, 0); //这个函数记录第一次出现的数组下标。
cout << “index” << index << endl;
string::iterator it = find(s1.begin(), s1.end(), “l”);
if (it != s1.end())
s1.erase(it);
cout << s1 << endl;
}