c++ string

来源:互联网 发布:机柜网络模块 编辑:程序博客网 时间:2024/05/16 19:44

(1)string大小

string str("hello");

string::size_type size=str.size();

size=str.length();

 

(2)string遍历

for(string::iterator it=str.begin();it!=str.end();it++)

{

    cout<<*it<<endl;

}

 

for(int n=0;n<str.size();n++)

{

 cout<<str.at(n);

}

 

(3)string是否为空

str.empty();

 

(4)string返回CHAR*

str.c_str();

 

(5)string清空

str.clear();

 

(6) string删除

 

 

// string::erase#include <iostream>#include <string>using namespace std;int main (){  string str ("This is an example phrase.");  string::iterator it;  // erase used in the same order as described above:  str.erase (10,8);  cout << str << endl;        // "This is an phrase."  it=str.begin()+9;  str.erase (it);  cout << str << endl;        // "This is a phrase."  str.erase (str.begin()+5, str.end()-7);  cout << str << endl;        // "This phrase."  return 0;}

 

(7)string  查找

 

// string::find#include <iostream>#include <string>using namespace std;int main (){  string str ("There are two needles in this haystack with needles.");  string str2 ("needle");  size_t found;  // different member versions of find in the same order as above:  found=str.find(str2);  if (found!=string::npos)    cout << "first 'needle' found at: " << int(found) << endl;  found=str.find("needles are small",found+1,6);  if (found!=string::npos)    cout << "second 'needle' found at: " << int(found) << endl;  found=str.find("haystack");  if (found!=string::npos)    cout << "'haystack' also found at: " << int(found) << endl;  found=str.find('.');  if (found!=string::npos)    cout << "Period found at: " << int(found) << endl;  // let's replace the first needle:  str.replace(str.find(str2),str2.length(),"preposition");  cout << str << endl;  return 0;}

 

原创粉丝点击