string类的成员函数
string类
string对象是一个特殊的容器,它的设计主要是为了方便对字符串的操作。
string类来自于这个类模板
typedef basic_string<char> string;
成员函数:
ITERATORS:
begin 返回首个迭代器
end 返回哨兵迭代器
rbegin 返回倒序的首个迭代器
rend 返回返回倒序的哨兵迭代器
CAPACITY:
size 返回字符串长度,不包括'\0'
length 同上
max_size 返回string对象所能容纳的最大字符个数
resize 调整字符串长度
capacity 返回所分配内存的大小
reserve 设置capacity的最小值
clear 清除string
empty 判断string是否为空
ELEMENT ACCESS:
operator[] C风格下标访问
at C++风格访问(会检查越界)
MODIFIERS:
operator+= 连接字符(串)
append 同上
push_back 添加单个字符
assign 赋值
insert 插入
erase 擦除
replace 取代
copy 复制子串
swap 交换两个字符串的内容
STRING OPERATION:
c_str 转换成'\0'结尾的C风格字符串
data 得到string的内容
get_allocator
find 找到第一次出现的位置
rfind 找到最后一次出现的位置
find_first_of Find character in string
find_last_of Find character in string from the end
find_first_not_ofFind absence of character in string
find_last_not_ofFind absence of character in string from the end
substr 得到子串
string对象是一个特殊的容器,它的设计主要是为了方便对字符串的操作。
string类来自于这个类模板
typedef basic_string<char> string;
成员函数:
ITERATORS:
begin 返回首个迭代器
end 返回哨兵迭代器
rbegin 返回倒序的首个迭代器
rend 返回返回倒序的哨兵迭代器
CAPACITY:
size 返回字符串长度,不包括'\0'
length 同上
max_size 返回string对象所能容纳的最大字符个数
resize 调整字符串长度
capacity 返回所分配内存的大小
reserve 设置capacity的最小值
clear 清除string
empty 判断string是否为空
ELEMENT ACCESS:
operator[] C风格下标访问
at C++风格访问(会检查越界)
MODIFIERS:
operator+= 连接字符(串)
append 同上
push_back 添加单个字符
assign 赋值
insert 插入
erase 擦除
replace 取代
copy 复制子串
swap 交换两个字符串的内容
STRING OPERATION:
c_str 转换成'\0'结尾的C风格字符串
data 得到string的内容
get_allocator
find 找到第一次出现的位置
rfind 找到最后一次出现的位置
find_first_of Find character in string
find_last_of Find character in string from the end
find_first_not_ofFind absence of character in string
find_last_not_ofFind absence of character in string from the end
substr 得到子串
compare 比较
// string constructor #include <iostream> #include <string> using namespace std; int main () { // constructors used in the same order as described above: string s1; string s5 ("Initial string"); string s2 (s5); string s3 (s5, 8, 3); string s4 (s5, 8); string s6 (10, 'x'); string s7a (10, 42); string s7b (s5.c_str(), s5.c_str()+4); cout << "s1: " << s1 << "\ns2: " << s2 << "\ns3: " << s3; cout << "\ns4: " << s4 << "\ns5: " << s5 << "\ns6: " << s6; cout << "\ns7a: " << s7a << "\ns7b: " << s7b << endl; return 0; } Output: s1: s2: Initial string s3: str s4: Initial s5: Initial string s6: xxxxxxxxxx s7a: ********** s7b: Init // string assigning #include <iostream> #include <string> using namespace std; int main () { string str1, str2, str3; str1 = "Test string: "; // c-string str2 = 'x'; // single character str3 = str1 + str2; // string cout << str3 << endl; return 0; }