1. String对象初始化
string初始化方法 |
解释 |
sting s; |
创建空的字符串; |
string s = “value”; |
用值value来初始化字符串s; |
string s(“value”); |
用值value来初始化字符串s; |
string s(s2); |
用字符串s2来初始化字符串s; |
string s(s2, pos); |
从s2的位置pos处开始到最后的所有字符来初始化s; |
string s(n, ‘c’); |
用n个字符c来初始化s; |
string s(b, e); |
用迭代器b到e之间的内容初始化字符串s; |
string s(chs, n); |
用从字符数组chs的前n个字符来初始化s; |
string s(s2, pos, len); |
从s2的第pos个位置开始的len个字符初始化s; |
#include<iostream>
#include<string>
int main()
{
std::string s1;
std::string s2 = "Come on, boy!";
std::string s3("Hello World, Welcome to C++!");
std::string s4(s3);
std::string s5(5, 's'); // sssss
std::string s6(s3.begin() + 6, s3.begin()+6+5); // World
std::string s7(s3, 6); // World, Welcome to C++!
char *chs = "Project Main."; // 字符指针表示字符串,该字符串的最后有一个'\0'
char ch2[] = "C plus plus!"; // 字符数组表示字符串,最后有一个'\0';
char ch3[] = { 'H', 'W' }; // 字符数组,后面没有'\0',因此不算是字符串;
std::string s8(chs, 7); // Project // 从chs开始的前面7个字符
std::string s9(ch2, 6); // C plus
std::string s10(ch2 + 7, 5); // plus! // 从chs第7个字符开始的后面5个字符
std::string s11(ch2); // C plus plus!
//std::string s11(ch3); // 报错,ch3后面没有'\0';
std::string s12(ch3, 2); // HW
std::string s13(chs, 8, 5); // Main. // 从chs的第8个位置开始的5个字符, plus!
std::string s14(chs, 8, 10); // Main. // 从chs的第8个位置开始的10个字符, 不够10个就取到chs的最后.
std::cout << s1 << std::endl;
std::cout << s2 << std::endl;
std::cout << s3 << std::endl;
std::cout << s4 << std::endl;
std::cout << s5 << std::endl;
std::cout << s6 << std::endl;
std::cout << s7 << std::endl;
std::cout << s8 << std::endl;
std::cout << s9 << std::endl;
std::cout << s10 << std::endl;
std::cout << s11 << std::endl;
std::cout << s12 << std::endl;
std::cout << s13 << std::endl;
std::cout << s14 << std::endl;
//system("pause");
return 0;
}
2. 修改String对象:
1.通用迭代器方法修改string对象
String对象修改方法 |
解释 |
s.insert(p, t); |
在迭代器 p 前面插入字符 t; |
s.insert(p, n, t); |
在迭代器 p 前面插入 n 个字符 t; |
s.insert(p, b, e); |
在迭代器 p 的位置插入迭代器 b 到 e 直接的所有元素; |
s.assign(b |