如何获取数组中字符串元素的字符数?[C++]

How do I get the number of character of a string element in a array? [C++]

本文关键字:字符 C++ 元素 字符串 何获取 获取 数组      更新时间:2023-10-16

示例:

string array[3] = {"Hello", "HI", "Goodbye"};
cout << len(array[0]) << endl;      //print out the number 5
cout << len(array[1]) << endl;      //print out the number 2
cout << len(array[2]) << endl;      //print out the number 7

我知道 len(( 函数在这个例子中不起作用。如何获取数组中每个字符串元素中的字符数?

提前谢谢。

由于元素是std::string的,你可以使用 length 成员:

cout << array[0].length() << endl;
使用 size(( 成员函数(

或 length(( 成员函数 - 它们是一回事(

cout << array[0].size() << endl;
cout << array[1].size() << endl;
cout << array[2].size() << endl;