C++ Primer(第五版)学习笔记_4_标准模板库string(1)
1、创建string对象
创建一个空字符串,其长度为0
#include <iostream> #include <string> using namespace std; int main(int argc, char* argv[]) { string s; cout << s.length() << endl; return 0; }
#include <iostream> #include <string> using namespace std; int main(int argc, char* argv[]) { string s; s = "hello, C++ STL."; cout << s << endl; return 0; }
#include <iostream> #include <stdio.h> #include <string> using namespace std; int main(int argc, char* argv[]) { string s1; char ss[5000]; //scanf的输入速度比cin快的多 //scanf是C语言的函数,不支持string对象 scanf("%s", &ss); s1 = ss; cout << s1 << endl; string s2; cin >> s2; cout << s2 << endl; return 0; }
#include <iostream> #include <stdio.h> #include <string> using namespace std; int main(int argc, char* argv[]) { string s; s = s + 'a'; s = s + 'b'; s = s + 'c'; cout << s << endl; return 0; }
#include <iostream> #include <stdio.h> #include <string> using namespace std; int main(int argc, char* argv[]) { string s; s = s + "abc"; s = s + "123"; cout << s << endl; return 0; }
#include <iostream> #include <stdio.h> #include <string> using namespace std; int main(int argc, char* argv[]) { string s; s.append("abc"); s.append("123"); cout << s << endl; return 0; }
#include <iostream> #include <stdio.h> #include <string> using namespace std; int main(int argc, char* argv[]) { string s; s = "123456"; s.insert(s.begin() + 1, 'p'); cout << s << endl; return 0; }
#include <iostream> #include <stdio.h> #include <string> using namespace std; int main(int argc, char* argv[]) { string s; s = "abc123456"; cout << s[0] << endl; cout << s[0] - 'a' << endl; return 0; }
#include <iostream> #include <stdio.h> #include <string> using namespace std; int main(int argc, char* argv[]) { string s; s = "abc123456"; //删除第3个元素,元素位置从0开始计数 s.erase(s.begin() + 3); cout << s << endl; //删除0~4左闭右开区间的所有元素,[0, 4) s.erase(s.begin(), s.begin() + 4); cout << s << endl; s = ""; cout << s.length() << endl; return 0; }
#include <iostream> #include <stdio.h> #include <string> using namespace std; int main(int argc, char* argv[]) { string s; s = "abc123456"; cout << s.length() << endl; cout << s.size() << endl; s.clear(); cout << s.empty() << endl; return 0; }
#include <iostream> #include <stdio.h> #include <string> using namespace std; int main(int argc, char* argv[]) { string s; s = "abc123456"; //从第3个开始,将连续的3个字符替换为"good" //即将"1234"替换为good s.replace(3, 4, "good"); cout << s << endl; return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
C++ Primer(第五版)学习笔记_4_标准模板库string(1)
原文地址:http://blog.csdn.net/keyyuanxin/article/details/46815957