获取字符串长度
string类型对象包括三种获取字符串长度的函数:size()
、length()
和max_size()
和capacity()
。
- size()和length():这两个函数会返回string类型对象的字符个数,且他们的执行效果相同。
- max_size():这个函数返回string类型对象最多包含的字符数。一旦超过这个长度,编译器就会抛出length_error异常。
- capacity():这个函数返回在重新分配内存之前,string类型对象所能包含的最大字符数。
示例:
#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;
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
length=8
maxsize=2147483647
capacity=15
在上述代码第14行与第15行加上:
str_custom.resize(5)
运行结果为:
size=5
length=5
maxsize=2147483647
capacity=15
获取字符串元素
字符串中元素的访问是允许的,一般可使用两种方法访问字符串中的单一字符:下标操作符[]
和成员函数at()
。两者均返回指定的下标位置的字符。第1个字符索引(下标)为 0,最后的字符索引为 length()-1。