C风格字符串(以空字符结尾的字符数组)太过复杂难于掌握,不适合大程序的开发,所以C++标准库定义了一种string类,定义在头文件<string>。
String和c风格字符串对比:
- Char*是一个指针,String是一个类
string封装了char*,管理这个字符串,是一个char*型的容器。
- String封装了很多实用的成员方法
查找find,拷贝copy,删除delete 替换replace,插入insert
- 不用考虑内存释放和越界
string管理char*所分配的内存。每一次string的复制,取值都由string类负责维护,不用担心复制越界和取值越界等。
常用方法
str.assign(string,end);截取字符串
str.assign(string,start,end);截取字符串
str.replace(start,num,string);start开始替换的位置,num替换多少个字符,string要替换的字符串
str.find(c);要查找的字符,或字符串
str.find(c,start);要查找的字符,或字符串,从start开始寻找
str.substr(start.length);从start开始截取length个字符
str.insert(pos,string);在pos的位置,插入string字符串
str.erase(pos,length);从pos的位置开始,删除length个
toupper(c);
tolower(c);
#include<iostream>
#include<string>
#include<vector>
using namespace std;
void test01() {
string str1 = "abc";
string str2 = "def";
str1 += str2;
cout <<"str1=" << str1 << endl;
string str3(str1);
cout <<"str3=" << str3 << endl;
string str4(10,'a');
cout << "str4=" << str4 << endl;
}
void test02() {
string str1 = "abc";
str1.assign("12345678900", 3);
cout <<"str1=" << str1 << endl;
string str2;
str2.assign("12345678900", 3,6);
cout << "str2=" << str2 << endl;
cout << "str2[2]=" << str2.at(2) << endl;
cout <<"str2 index=" << str2.find("67") << endl;
str2.replace(1,0,"asdasd");
cout << "str2.replace=" << str2 << endl;
if (str2.compare(str1) == 0) {
//if (str2==str1) {
cout << "str2==str1" << endl;
}
else if (str2.compare(str1) > 0) {
//else if (str2>str1) {
cout << "str2>str1" << endl;
}
else {
cout << "str2<str1" << endl;
}
}
void test03() {
vector <string> vs;
int start = 0;
int pos = 0;
string url = "www.node.js.org";
while (1) {
pos=url.find(".",start);
if (pos == -1) {
string temp = url.substr(start, url.length()-1);
vs.push_back(temp);
break;
}
string temp = url.substr(start, pos-start);
start = pos+1;
vs.push_back(temp);
}
for (vector<string> ::iterator i = vs.begin(); i != vs.end(); ++i) {
cout << (*i) << endl;
}
}
void test04() {
string str1 = "abcdefghijklmn";
str1.insert(1, "1234");
cout << "str1=" << str1 << endl;
str1.erase(1,4);
cout << "str1=" << str1 << endl;
cout << "toupper=" << toupper(str1[0]) << endl;
}
void test05() {
//隐式类型转换,可以转为string
string str1 = "abcdefg";
str1.c_str();
cout << str1 << endl;
string s(str1);
cout << str1 << endl;
}
int main() {
test01();
cout << "----------------------" << endl;
test02();
cout << "----------------------" << endl;
test03();
cout << "----------------------" << endl;
test04();
cout << "----------------------" << endl;
test05();
system("pause");
return EXIT_SUCCESS;
}