您可以使用
size()
函数或
length()
函数获取字符串对象的长度。
size()
和
length()
函数只是同义词,它们的作用完全相同。
示例: 字符串对象的长度
#include <iostream> using namespace std; int main() { string str = "C++ Programming"; // you can also use str.length() cout << "String Length = " << str.size(); return 0; }
输出
String Length = 15
示例: C 样式字符串的长度
要获取 C 字符串字符串的长度,使用
strlen()
函数。
#include <iostream> #include <cstring> using namespace std; int main() { char str[] = "C++ Programming is awesome"; cout << "String Length = " << strlen(str); return 0; }
输出
String Length = 26