本文主要是记录c++ string的常用成员函数。
1 string的常用成员函数
1.1 string的构造方法
1
2
3
4
5
6
7
8
9
10
11
12
|
std::string s("Exemplar");
std::string const other("Exemplar");
std::string s(other);
std::string const other("Exemplary");
std::string s(other, 0, other.length()-1);
std::string s(4, 'a'); // "aaaa"
char mutable_c_str[] = "another C-style string";
std::string s(std::begin(mutable_c_str)+8, std::end(mutable_c_str)-1);
|
1.2 获取字符串长度:size(), length()
1
2
3
|
std::string s("Exemplar");
assert(8 == s.size());
assert(s.size() == s.length());
|
1.3 字符串查找:find()
1
2
3
4
5
6
7
8
9
|
// find(): Finds the first substring equal to the given character sequence.
// rfind(): Finds the last substring equal to the given character sequence.
string src = "This is a test."
string::size_type index = src.find("is");
if (index != string::npos) {
cout << "Found, index:" << index << endl;
} else {
cout << "Not found." << endl;
}
|
1.4 字符串连接
1.4.1 使用string::append()
示例:
1
2
3
4
5
6
7
|
string str1("foo");
string str2(" bar");
str1.append(str2);
cout << str1 << endl; // print "foo bar"
return 0;
|
1.4.2 使用连接运算符(+)
1
2
3
4
5
6
7
|
string str1("foo");
string str2(" bar");
str1 = str1 + str2;
cout << str1 << endl; // print "foo bar"
return 0;
|
1.4.3 使用库函数:strcat()
1
2
3
4
5
6
7
|
string str1("foo");
string str2(" bar");
strcat(str1, str2);
cout << str1 << endl; // print "foo bar"
return 0;
|
1.4.3 使用循环
1
2
3
4
5
6
7
8
|
string str1("foo");
string str2(" bar");
for (auto i : str2) {
str1 += i;
}
cout << str1 << endl; // print "foo bar"
return 0;
|
1.5 C++ string与C字符串互转
1
2
3
4
5
6
7
8
9
10
|
//string转换为C字符串
string str = "abc";
char arr[100];
strncpy(arr, str.c_str(), str.size());
//c字符串转换为string
char cStr[] = "hello";
string str(cStr);
|
1.6 分割字符串:substr()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
vector<string> SplitString(const string& sourceStr, const string& delimiter)
{
string tmp = sourceStr;
vector<string> output;
size_t pos = 0;
string token;
while ((pos = tmp.find(delimiter)) != string::npos)
{
token = tmp.substr(0, pos);
cout << token << endl;
output.push_back(token);
tmp.erase(0, pos + delimiter.length());
}
cout << tmp << endl;
output.push_back(tmp);
return output;
}
|