一、另类的构造方式
1. string s(cp, n)
s是cp指向的数组中前n个字符的拷贝。//此数组应该至少包含n个字符
char cp[] = "i am a cp array";
std::string s(cp, 9);
std::cout << s << std::endl;
输出:
i am a cp
2.string s(s2, pos2)
s是string s2从下标pos2开始的字符的拷贝。
std::string s2 = "i am s2";
std::string s(s2, 2);
std::cout << s << std::endl;
输出:
am s2
3.string s(s2, pos2, len2)
s是string s2从下标pos2开始len2个字符的拷贝。最多拷贝到s2的最后。
std::string s2 = "i am s2";
std::string s(s2, 2, 4);
std::cout << s << std::endl;
输出:
am s
二、find和substr
1、find使用
size_type find(const basic_string& __str, size_type __pos = 0)
返回值为字符串中初次找到子字符串str时的下标。pos为起始查找的位置。如果搜索失败,则返回std::string::npos。
std::string s = "i will test find test";
auto pos = s.find("test");
std::cout << s << " " << pos << std::endl;
输出
i will test find test 7
2、rfind使用
size_type rfind(const basic_string& __str, size_type __pos = 0)
返回值为字符串中最后一次找到子字符串str时的下标。pos为起始查找的位置。如果搜索失败,则返回std::string::npos。
std::string s = "i will test find test";
auto pos = s.rfind("test");
std::cout << s << " " << pos << std::endl;
输出
i will test find test 17
3、substr使用
string substr (size_t pos = 0, size_t len = npos) const;
在字符位置pos开始,拷贝len个字符(或直到字符串的结尾)。
std::string s = "i will test find test";
std::string s2 = s.substr(2, 9);
std::cout << s2 << std::endl;
输出
will test
配合find使用更佳
string substr (size_t pos = 0, size_t len = npos) const;
在字符位置pos开始,拷贝len个字符(或直到字符串的结尾)。
std::string s = "i will test find test";
auto pos = s.find("test");
std::string s2 = s.substr(pos);
std::cout << s2 << std::endl;
输出
test find test