C++获取字符串长度详解
发布时间:2020-12-16 07:38:14 所属栏目:百科 来源:网络整理
导读:String 类型对象包括三种求解字符串长度的函数: size() 和 length() 、 maxsize()? 和 capacity() : size() 和 length():这两个函数会返回 string 类型对象中的字符个数,且它们的执行效果相同。 max_size():max_size() 函数返回 string 类型对象最多包含
String 类型对象包括三种求解字符串长度的函数:size() 和 length()、 maxsize()?和 capacity():
string 类型对象还包括一个 reserve() 函数。调用该函数可以为 string 类型对象重新分配内存。重新分配的大小由其参数决定。reserve() 的默认参数为 0。 上述几个函数的使用方法如下程序所示: #include <iostream> #include <string> using namespace std; int main () { ??? int size = 0; ??? int length = 0; ??? unsigned long maxsize = 0; ??? int capacity=0; ??? string str ("12345678"); ??? string str_custom; ??? str_custom = str; ??? str_custom.resize (5); ??? size = str_custom.size(); ??? length = str_custom.length(); ??? maxsize = str_custom.max_size(); ??? capacity = str_custom.capacity(); ??? cout << "size = " << size << endl; ??? cout << "length = " << length << endl; ??? cout << "maxsize = " << maxsize << endl; ??? cout << "capacity = " << capacity << endl; ??? return 0; }程序执行结果为:
size = 8 修改上述代码,删除语句 str_custom.reserve (5),在代码 str_custom = str 之后如下添加代码: str_custom.resize (5); 修改后程序的执行结构如下:
size = 5 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |