string 用法

来源:互联网 发布:大富豪5.3棋牌源码 编辑:程序博客网 时间:2024/04/29 17:13
/*  Name:   Copyright:   Author:   Date: 18/07/11 13:25  Description:       the way to use string.      some important princinple*/#include<iostream>#include<string> #include<cctype> //this lib contain some funtion of character  c++ overwrite some C libary. the name<file.h> change to <Cfile> using std::string; // it is more  efficiency and brief than using namespaceusing std::cout;using std::endl;                   // stdandar libary declare ,all the standar libary is in the namespace std;int main(){   //注意初始化,包括分配空间和初始化,分配的空间一般比初始化字串空间大。动态管理内存。在Heap里分配    string strDefault; //default construct fuction. alloc some space(8byte),string object init "";   string strTestValue("value");//use the string value inti   string strTestCopy(strTestValue);// string copy inti   string strTestCharacter(10,'0'); //inti the character in string   // careful the following is wrong   //string strDefualt = "hello" + "word"; // 字符串面值不等于字符串对象这里和java等语言不一样。   strDefault = strTestValue + strTestCharacter; // 分两步,首先 strTestVlaue + strTestCharacter   //是字符串重载调用 string& operator +(const string& strScr); 返回的是左值引用类型。(查看空间够不够,不够了   //重新开空间复制。   string 拷贝构造,==调用的是。 开空间复制   string strAssign("hello,word!");    int iCount = 0;   // string::size_type string里面自定义类型,千万比复制给int,size_type unsigned long    //在string的操作小标长度,最好用size_type   //,at() funtion 相比【】更安全下,有下表越界检查。两者返回都是左值    for(string::size_type iIndex = 0 ; iIndex < strAssign.size(); iIndex++)   {       if(ispunct(strAssign.at(iIndex))) //judge symbol        {           iCount++;       }           strAssign.at(iIndex) = toupper(strAssign.at(iIndex)); //to upper          }       cout<<iCount<<endl;   system("pause");   return 0;}    


 

原创粉丝点击