如何检查字符串是否在字符串数组中[重复]

2024-04-21

#include <iostream>
#include <string>
using namespace std;

bool in_array(string value, string *array)
{
    int size = (*array).size();
    for (int i = 0; i < size; i++)
    {
        if (value == array[i])
        {
            return true;
        }
    }

    return false;
}

int main() {
    string tab[2] = {"sdasd", "sdsdasd"};
    string n;
    cin >> n;
    if (in_array(n, tab)) {

    }
    return 0;
}

我想检查 C++ 是否n字符串位于tab数组,但代码返回错误。 我做错了什么?也许我应该使用向量?


int size = (*array).size();

它不会告诉你尺寸array,它告诉您该数组中第一个字符串的长度,您应该将数组的长度单独传递给函数。该函数应如下所示:

bool in_array(string value, string *array, int length)

 

但更好的选择是使用std::vector and std::find:

#include <vector>
#include <algorithm>


bool in_array(const std::string &value, const std::vector<std::string> &array)
{
    return std::find(array.begin(), array.end(), value) != array.end();
}

然后,您可以像这样使用它:

std::vector<std::string> tab {"sdasd", "sdsdasd"};

if (in_array(n, tab))
{
    ...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何检查字符串是否在字符串数组中[重复] 的相关文章

随机推荐