如何在c ++中查找字符串数组中的元素数量?

时间:2011-04-21 04:05:39

标签: c++

我有一个字符串数组。

std :: string str [10] = {“one”,“two”}

如何查找str[]数组中有多少个字符串?有标准功能吗?

7 个答案:

答案 0 :(得分:6)

尽管您只初始化了其中两个字符串,但仍有十个字符串:

#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

答案 1 :(得分:6)

如果你想计算所有元素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;
 }

答案 2 :(得分:1)

我不知道我会使用std :: strings数组。如果您已经在使用STL,为什么不考虑矢量或列表?至少就是这样你可以用std :: vector :: size()来解决它,而不是使用丑陋的sizeof魔法。此外,如果数组存储在堆而不是堆栈上,那魔法大小将无效。

这样做:

std::vector<std::string> strings(10);
strings[0] = "one";
strings[1] = "two";

std::cout << "Length = " << strings.size() << std::endl;

答案 3 :(得分:0)

您总是可以使用countof宏来获取元素的数量,但同样,内存被分配给10个元素,这就是您将获得的计数。

答案 4 :(得分:0)

理想的方法是

std::string str[] = {"one","two"}

int num_of_elements = sizeof( str ) / sizeof( str[ 0 ] );

答案 5 :(得分:0)

因为你知道大小。 你可以做二进制搜索not null / empty。

str [9]是空的 str [5]是空的 str [3]不是空的 str [4]是空的 你有4个项目。

我真的不想实现代码,但这会非常快。

答案 6 :(得分:0)

只需将此函数用于1D字符串数组:

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

我只是想知道我们是否可以为此编写模板元程序! (因为在编译时一切都已知)

相关问题