给定字符串和单词 S 的列表,检查列表中是否存在 S
Given a list of strings and word S. Check if S exists in the list or not
/* 此代码中的错误是什么?我总是得到假(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;
}
相关文章:
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 模板化检查是否存在带有参数列表的类成员函数?
- 如何检查C ++ STL列表是否为回文?
- 如何在C中检查随机数列表中的元素
- 我可以检查初始化列表中设置的构造函数主体中的变量吗
- 使用 Numpy 进行快速列表检查
- 给定字符串和单词 S 的列表,检查列表中是否存在 S
- 有没有办法接受某些输入的第一个字母并检查它是否在某个列表中?
- 如何在不使用循环或迭代器的情况下检查所有列表元素并在满足条件时删除一个
- 卡在 if 语句中,以检查列表中的数字
- C++初始值设定项列表约束检查
- Bool排序的插入函数,检查列表中是否已经存在int
- 我的列表类别的C SEG故障,但似乎都在检查
- Boost检查该类型是否属于给定类型的列表
- 检查使用初始化列表时传递给构造函数的参数 - C++
- 使用TBB的并行性-我们的检查列表中应该包含哪些内容
- 算法-检查数字是否已经在列表中
- 在隐式构造函数中未检查C++11初始值设定项列表长度
- 首次机会异常设置检查列表视图中的状态
- 检查初始值设定项列表中的空向量