STL的string的基本操作

来源:互联网 发布:红色警戒3起义时刻mac 编辑:程序博客网 时间:2024/05/16 19:33

/*  对STL的string进行练习: * string的初始化、遍历、拷贝、连接、查找和替换*/#pragma warning(disable : 4996) #include <iostream>#include <string>#include <iterator>
#include <algorithm>using namespace std;void main(){/** string串的初始化方法*/string s1 = "abcdefv";string s2(4, 'z');string s3 = s2; //USE COPY FUNCTIONstring s4("httcc");/* *  string的遍历*/for (int i = 0; i < s1.length(); ++i){cout << s1[i] << " ";}cout << endl;// OUTPUT STRING DIRECTLYcout << s2.c_str() << endl;// USE ITERATIRfor (string::iterator it = s4.begin(); it != s4.end(); ++it){cout << *it << " ";} cout << endl;// USE at(), can throw the exception, safely than using array indexfor (int i = 0; i < s1.length(); ++i){cout << s1.at(i) << " ";}cout << endl; /** string的拷贝 str.copt()函数*/char buf[10] = { 0 };s1.copy(buf, 5, 0);cout << buf << endl;/** string 的连接*/s3 = s3 + s4;cout << s3 << endl;s4.append(s3);cout << s4 << endl<<endl;/** string 的查找和替换*/// FIND string “ere”string s5 = "Where there is a will, there is a way.";int ind1 = s5.find("ere",0);cout << s5 << endl;cout << ind1 << endl;// FIND the count of "ere" existsint count = 0;string s6 = { 0 };while (ind1 != string::npos){++count;cout << "index: " << ind1 << endl;// REPLACE string“ere”s6 = s5.replace(ind1, 3, "vvv");ind1 = ind1 + 1;ind1 = s5.find("ere", ind1);}cout << "\"ere\"出现次数:" << count << endl << endl;cout << "Replace \"ere\" to \"vvv\": " <<endl<<s6 << endl;
/** string 的插入和删除*///INSERTstring s7 = "To be or to be";cout << s7 << endl;s7.insert(8," not");cout << s7 << endl;s7.insert(18, 4, 'e');cout << s7 << endl << endl;//ERASE: 2 wayss7.erase(18, 4);cout <<"After erase 'eee': "<< s7 << endl;string::iterator it = find(s7.begin(), s7.end(), 'o');while (it != s7.end()){s7.erase(it);}cout <<"After erase the first 'o': "<< s7 << endl;
/** string 的相关算法*/string s8 = "ABCDeoOOl";transform(s8.begin(),s8.end(),s8.begin(),toupper);cout << s8 << endl;transform(s8.begin(), s8.end(), s8.begin(), tolower);cout << s8 << endl;
cout << endl;}


注意:

1、【string::npos】npos 是一个常数,用来表示不存在的位置。类型一般是std::container_type::size_type 。
许多容器都提供这个东西,取值由实现决定,一般是-1。这样做,就不会存在移植的问题了。

2、头文件前面要加上 #pragma warning(disable : 4996)  ,否则VS2013会报错:

error C4996: 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>::copy': Function call with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators'


原创粉丝点击