C++之STL -- string
1.string和char *的区别
(1)string是一个类,char *是一个指向字符的指针。
(2)string不用考虑内存释放和越界。
(3)string提供了一系列字符串操作函数:find,copy,erase,replace,insert等。
2.string的构造函数及遍历
#include <iostream>
#include <string>
using namespace std;
int main()
{
/* 字符串的四种构造方法 */
string s1 = "hello";
string s2("haha");
string s3 = s2;
string s4(5,'a');
cout << s4 << endl; //aaaaa
/* 字符串遍历的方法 */
//1.数组方式
for(int i=0;i<s1.length();i++)
{
cout << s1[i] << " ";
}
cout << endl;
//2.迭代器
for(string::iterator it = s1.begin();it!=s1.end();it++)
{
cout << *it << " ";
}
cout << endl;
return 0;
}
3.string类存取字符的操作
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "hello";
for(int i=0;i<s1.length();i++)
{
cout << s1.at(i) << " "; //抛出异常
}
return 0;
}
4.字符指针和string的对换
5.连接字符串
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "hello";
string s2 = "world";
s1 = s1 + s2;
cout << s1 << endl;
string s3 = "hello";
string s4 = "c++";
s3.append(s4);
cout << s3 << endl;
return 0;
}
6.字符串查找和替换(重点)6.字符串查找和替换(重点)
API如下:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "hello Java,hello C#,hello C++,hello Python";
//第一次出现hello的index
int index = s1.find("hello",0);
cout << index << endl;
//求hello出现的次数以及每一次出现的数组下标
int offindex = s1.find("hello",0);
while (offindex != string::npos)
{
cout << offindex << endl;
offindex = offindex+1;
offindex = s1.find("hello",offindex);
}
return 0;
}
7.string的典型操作:删除和插入
(1)删除操作:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string s1 = "hello1 hello2 hellol";
string::iterator it = find(s1.begin(),s1.end(),'1');
if (it != s1.end())
{
s1.erase(it);
}
cout << s1 << endl;
s1.erase(s1.begin(),s1.end()); //全部删除
cout << s1.length() << endl;
return 0;
}
(2)插入操作:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string s1 = "aaa";
s1.insert(0,"hahaha"); //头部插入
s1.insert(s1.length(),"---"); //尾部插入
cout << s1 << endl;
return 0;
}
8.大小写转换
#include <stdio.h>
#include <string.h> //strlen
#include <ctype.h> //toupper
using namespace std;
int main()
{
int i;
char s[] = "HELLO WORLD";
for(i=0;i<strlen(s);i++)
{
s[i] = tolower(s[i]);
}
printf("%s\n",s);
return 0;
}