在C++中,可以通過string對象的size()或length()方法來獲取字符串的長度。示例如下:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
// 使用size()方法獲取字符串長度
std::cout << "Length of string (using size()): " << str.size() << std::endl;
// 使用length()方法獲取字符串長度
std::cout << "Length of string (using length()): " << str.length() << std::endl;
return 0;
}
以上代碼會輸出:
Length of string (using size()): 13
Length of string (using length()): 13