gpt4 book ai didi

c++ - 如何检查字符串是否在字符串数组中

转载 作者:IT老高 更新时间:2023-10-28 22:11:06 26 4
gpt4 key购买 nike

#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;
}

如果 n 字符串在 tab 数组中,我想检查 C++,但代码返回错误。我做错了什么?也许我应该使用 vector ?

最佳答案

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

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

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

 

但更好的选择是使用 std::vectorstd::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))
{
...
}

关于c++ - 如何检查字符串是否在字符串数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20303821/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com