此函数用于返回以字节为单位的字符串长度。它定义了符合字符串对象内容的实际字节数,不一定等于容量。
size - 语法
考虑一个名为str的字符串对象。要计算此字符串对象的大小,其语法为:
str.size()
size - 返回值
此函数返回字符串对象中存在的字符数。
size - 例子1
#include<iostream> using namespace std; int main() { string str ="Welcome to the learnfk tutorial"; int size = str.size(); cout << "length of the string is :" <<size; return 0; }
输出:
length of the string is : 30
在此示例中,str是一个字符串对象,包含值" Welcome to the learnfk tutorial"。我们使用size函数计算字符串的长度。