我有一个字符串数组。
std::string str[10] = {"one","two"}
如何查找 str[]
数组中有多少个字符串?是否有标准函数可用?
我有一个字符串数组。
std::string str[10] = {"one","two"}
如何查找 str[]
数组中有多少个字符串?是否有标准函数可用?
尽管您仅初始化了其中两个字符串,但是其中有十个字符串:
#include <iostream>
int main (void) {
std::string str[10] = {"one","two"};
std::cout << sizeof(str)/sizeof(*str) << std::endl;
std::cout << str[0] << std::endl;
std::cout << str[1] << std::endl;
std::cout << str[2] << std::endl;
std::cout << "===" << std::endl;
return 0;
}
10
one
two
===
#include <iostream>
int main (void) {
std::string str[10] = {"one","two"};
size_t count = 0;
for (size_t i = 0; i < sizeof(str)/sizeof(*str); i++)
if (str[i] != "")
count++;
std::cout << count << std::endl;
return 0;
}
这将如预期地输出2
。
count--
,将null更改为非null -> count++
)。(3) 是的,我错过了,会改变的。但是,如果你有那么多字符串,你比整数溢出还要麻烦 :-) - paxdiablo如果你想计算所有元素,可以使用sizeof
技术,就像其他人指出的那样。
如果你想计算所有非空字符串,这是一种可能的方法,可以使用标准的count_if
函数。
bool IsNotEmpty( const std::string& str )
{
return !str.empty();
}
int main ()
{
std::string str[10] = {"one","two"};
int result = std::count_if(str, &str[10], IsNotEmpty);
cout << result << endl; // it will print "2"
return 0;
}
find_if(..., IsEmpty)
。 - Tony Delroy我不确定我会使用std::string数组。如果您已经在使用STL,为什么不考虑使用vector或list呢?至少这样你可以直接使用std::vector::size()来计算大小而不必使用丑陋的sizeof技巧。而且,如果数组存储在堆上而不是栈上,那么这种sizeof技巧将无法工作。
只需要这样做:
std::vector<std::string> strings(10);
strings[0] = "one";
strings[1] = "two";
std::cout << "Length = " << strings.size() << std::endl;
vector<>
来查找大小是一个很好的想法,非常直接。 - iammilind对于一维字符串数组,只需使用此函数:
template<typename String, uint SIZE> // String can be 'string' or 'const string'
unsigned int NoOfStrings (String (&arr)[SIZE])
{
unsigned int count = 0;
while(count < SIZE && arr[count] != "")
count ++;
return count;
}
使用方法:
std::string s1 = {"abc", "def" };
int i = NoOfStrings(s1); // i = 2
我在想我们是否可以为此编写一个模板元程序!(因为所有内容都在编译时已知)
您可以始终使用countof
宏来获取元素的数量,但是请注意,内存是为10个元素分配的,这也是您将获得的计数。
最理想的方法是这样做:
std::string str[] = {"one","two"}
int num_of_elements = sizeof( str ) / sizeof( str[ 0 ] );
因为你知道大小,你可以使用二分搜索找到非空的值。
str[9] 是空的
str[5] 是空的
str[3] 不为空
str[4] 是空的
你有4个项目。
我真的不想实现这段代码,但这应该会很快。
size_t stringArrSize(std::string *stringArray) {
size_t num = 0;
while (stringArray->empty() != true) {
++num;
stringArray++;
}
return num;
}