在C++中,length函數通常用于獲取字符串的長度。它可以用于std::string和C風格的字符串。
對于std::string,可以使用string的成員函數size()或length()來獲取字符串的長度。示例如下:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::cout << "Length of the string: " << str.length() << std::endl;
return 0;
}
對于C風格的字符串,可以使用strlen函數來獲取字符串的長度。示例如下:
#include <iostream>
#include <cstring>
int main() {
const char *str = "Hello, World!";
std::cout << "Length of the string: " << strlen(str) << std::endl;
return 0;
}
總的來說,length函數用于獲取字符串的長度,可以用于std::string和C風格的字符串。