- 2
- 0
- 约1.46万字
- 约 15页
- 2017-10-22 发布于北京
- 举报
C中string的sizelengthcapacity三者到底有何区别求解
C++中string的size,length,capacity三者到底有何区别求解啦?
(2013-11-22 11:23:34)
#includeiostream#includestringusing namespace std;void Display(const string str){ coutString: strendl; coutSize: str.size()endl; coutLength: str.length()endl; coutCapacity: str.capacity()endl; coutMaxsize: str.max_size()endl; coutendlendl;}int main(){ string s1; Display(s1); s1.resize(23); Display(s1); string s2=123456; Display(s2); string s3=123 456 asd; Display(s3); s3.resize(23); Display(s3); return 0;}
C++STRING类常用函数
(2013-11-22 15:01:35)
转载▼
分类: C加加 C++STRING类常用函数
C++string类常用函数string类的构造函数:string(const char *s); //用c字符串s初始化string(int n,char c); //用n个字符c初始化此外,string类还支持默认构造函数和复制构造函数,如string s1;string s2=hello;都是正确的写法。当构造的string太长而无法表达时会抛出length_error异常string类的字符操作:const char operator[](int n)const;const char at(int n)const;char operator[](int n);char at(int n);operator[]和at()均返回当前字符串中第n个字符的位置,但at函数提供范围检查,当越界时会抛出out_of_range异常,下标运算符[]不提供检查访问。const char *data()const;//返回一个非null终止的c字符数组const char *c_str()const;//返回一个以null终止的c字符串int copy(char *s, int n, int pos = 0) const;//把当前串中以pos开始的n个字符拷贝到以s为起始位置的字符数组中,返回实际拷贝的数目string的特性描述:int capacity()const; //返回当前容量(即string中不必增加内存即可存放的元素个数)int max_size()const; //返回string对象中可存放的最大字符串的长度int size()const; //返回当前字符串的大小int length()const; //返回当前字符串的长度bool empty()const; //当前字符串是否为空void resize(int len,char c);//把字符串当前大小置为len,并用字符c填充不足的部分string类的输入输出操作:string类重载运算符operator用于输入,同样重载运算符operator用于输出操作。函数getline(istream in,string s);用于从输入流in中读取字符串到s中,以换行符\n分开。string的赋值:string operator=(const string s);//把字符串s赋给当前字符串string assign(const char *s);//用c类型字符串s赋值string assign(const char *s,int n);//用c字符串s开始的n个字符赋值string assign(const string s);//把字符串s赋给当前字符串string assign(int n,char c);//用n个字符c赋值给当前字符串string assign(const string s,int start,int n);//把字符串s中从start开始的n个字符赋给当前字符串string assign(const_iterator first,const_itertor last);//把first和
原创力文档

文档评论(0)