c++获取字符串长度的方法
时间: 2024-05-02 09:17:38 浏览: 183
在 C++ 中,获取字符串长度的方法有以下几种:
- 使用标准库函数 strlen(),该函数接受一个字符串参数,返回字符串的长度,不包括字符串末尾的空字符 '\0'。例如:
#include <cstring>
#include <iostream>
int main() {
char str[] = "Hello, world!";
std::cout << "The length of str is " << strlen(str) << std::endl;
return 0;
}
- 使用字符串类 std::string 的成员函数 size(),该函数返回字符串的长度,包括字符串末尾的空字符 '\0'。例如:
#include <string>
#include <iostream>
int main() {
std::string str = "Hello, world!";
std::cout << "The length of str is " << str.size() << std::endl;
return 0;
}
- 使用字符串类 std::string 的成员函数 length(),该函数返回字符串的长度,包括字符串末尾的空字符 '\0',与 size() 函数功能相同。例如:
#include <string>
#include <iostream>
int main() {
std::string str = "Hello, world!";
std::cout << "The length of str is " << str.length() << std::endl;
return 0;
}
相关推荐















