使用 C++ 字符串数组中有多少个字符?
Using C++ how many characters are in a string array?
我有下面的一段代码,我对它很困惑。我试图弄清楚有多少内存(memory/space 的字节实际上被我部分填充的数组占用了)。我有下面的代码,但我有点困惑。
如果我声明一个包含 8 个元素的字符串数组,并用这两个字符串部分填充元素。 for 循环将从 0 开始,直到我的数组大小 32 个可能的字节(假设每个字符串需要 4 个字节)除以数组中第一个元素的大小。即 returns 4 - 数组中第一个字符串的元素的大小。但这仍然没有告诉我该字符串中有多少 letters/characters。
我理解在循环中,当数组中的值不等于 blank/null 值时,我们会递增计数。为我们提供数组中的总填充(非空)位置。但是,我仍然没有实际字符数的值。
这如何告诉我们我的字符串中有多少个字符?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string test_array[8] = {"henry", "henry2"};
size_t count = 0;
for (size_t i = 0; i < sizeof(test_array)/sizeof(*test_array); i++)
{
cout << "NOT THE POINTER: "<<sizeof(test_array) << endl;
cout << "POINTER: "<<sizeof(*test_array) << endl;
if(test_array[i] != "")
count ++;
}
int num_elem = sizeof(test_array)/sizeof(test_array[0]);
cout << num_elem << endl;
cout << count << endl;
return 0;
}
要知道 std::string
中有多少个字符,请使用 size()
方法。
我有下面的一段代码,我对它很困惑。我试图弄清楚有多少内存(memory/space 的字节实际上被我部分填充的数组占用了)。我有下面的代码,但我有点困惑。
如果我声明一个包含 8 个元素的字符串数组,并用这两个字符串部分填充元素。 for 循环将从 0 开始,直到我的数组大小 32 个可能的字节(假设每个字符串需要 4 个字节)除以数组中第一个元素的大小。即 returns 4 - 数组中第一个字符串的元素的大小。但这仍然没有告诉我该字符串中有多少 letters/characters。
我理解在循环中,当数组中的值不等于 blank/null 值时,我们会递增计数。为我们提供数组中的总填充(非空)位置。但是,我仍然没有实际字符数的值。
这如何告诉我们我的字符串中有多少个字符?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string test_array[8] = {"henry", "henry2"};
size_t count = 0;
for (size_t i = 0; i < sizeof(test_array)/sizeof(*test_array); i++)
{
cout << "NOT THE POINTER: "<<sizeof(test_array) << endl;
cout << "POINTER: "<<sizeof(*test_array) << endl;
if(test_array[i] != "")
count ++;
}
int num_elem = sizeof(test_array)/sizeof(test_array[0]);
cout << num_elem << endl;
cout << count << endl;
return 0;
}
要知道 std::string
中有多少个字符,请使用 size()
方法。