给定字符串和单词 S 的列表,检查列表中是否存在 S

Given a list of strings and word S. Check if S exists in the list or not

本文关键字:列表 检查 存在 是否 字符串 单词      更新时间:2023-10-16

/* 此代码中的错误是什么?我总是得到假(0(,即使 字符串包含在列表中。上述问题的逻辑是否正确? */

#include <iostream>
using namespace std;
bool ispresent(char (*stringlist)[100] , char *arr){
for (int i = 0 ; i < 7 ; i++){
if (stringlist[i] == arr){
return true;
}
}
return false;
}
int main(){
//given  a list of strings
char stringlist[7][100] ={ 
"He",
"is",
"very",
"bad",
"instead",
"do",
"yourself"
};
//input word to check
char arr[50];
cin.getline(arr , 50 , 'n');
//check if word is present or not
bool found = ispresent(stringlist , arr) ;
cout << found;
return 0;
}

您应该使用字符串比较函数而不是 ==。它不适用于字符串。例:

strcmp(stringlist[i], arr)

并包含库字符串.h 比较运算符适用于原始变量而不是指针。当使用表示其他类型的数据的指针时,你应该实现自己的方法/函数(或使用库提供的方法/函数(,因为 == 运算符只比较引用,而不是它们引用的内容。

if (stringlist[i] == arr(

你总是得到false的原因是因为你使用的是==运算符,它将始终比较c字符串的一个元素而不是字符串的整个部分。string::find()是什么工作。

您应该尽可能使用 std::string,这样您就不必分配/释放内存。在 std::string 中有一个str.find(str1)函数,它给出了在 str 中找到 str1 的第一个索引。你可以以这种方式使用它

有关string::npos的信息: 从 cplusplus.com:

静态常量 size_t NPOS = -1;
size_t的最大值

此值,当用作 len(或 sublen(参数的值时 字符串的成员函数,意思是"直到字符串的末尾"。

作为返回值,它通常用于指示没有匹配项。

此常量定义为值 -1,由于 size_t 是>无符号整数类型,因此它是此类型的最大可能表示值>。

这应该有效:

#include <iostream>
#include <string>
// str is the string array
// str_size is the size of the array passed to the funcion
// str 1 is the string you are looking for.
bool ispresent(std::string str[], int str_size, std::string str1);
int main()
{
const int SIZE = 4;
std::string str0[SIZE];
std::cout << "Enter four strings:n";
for (int i = 0; i < 4; i++)
std::cin >> (str0)[i];
std::string search_term;
std::cout << "Enter a search term:";
std::cin >> search_term;
bool result = ispresent(str0, SIZE, search_term);
// If output is 1 then it was found
std::cout << result;
return 0;
}
bool ispresent(std::string str[], int str_size, std::string str1)
{
for (int i = 0; i < str_size; i++)
{
// Use the find function in string on each element of the array.
if (str[i].find(str1) != std::string::npos)
return true;    // Return true if found
}
// String not found
return false;
}