我想在句子列表中找到特定的字符串。每个句子都是用\n
分隔的一行。到达换行符后,当前搜索应停止并在下一行开始新的搜索。
我的程序是:
#include <iostream>
#include <string.h>
using namespace std;
int main(){
string filename;
string list = "hello.txt\n abc.txt\n check.txt\n"
cin >> filename;
// suppose i run programs 2 times and at 1st time i enter abc.txt
// and at 2nd time i enter abc
if(list.find(filename) != std::string::npos){
//I want this condition to be true only when user enters complete
// file name. This condition also becoming true even for 'abc' or 'ab' or even for 'a' also
cout << file<< "exist in list";
}
else cout<< "file does not exist in list"
return 0;
}
有没有办法。我只想在列表中找到文件名
最佳答案
首先,我不会将文件列表保留在单个字符串中,但是会使用任何类型的列表或向量。
然后,如果将列表保留在字符串中是您的必要(出于某种原因,在您的应用程序逻辑中),我会将字符串分隔为向量,然后循环遍历向量的元素,检查该元素是否恰好是所搜索的元素。
要拆分元素,我将要做:
std::vector<std::string> split_string(const std::string& str,
const std::string& delimiter)
{
std::vector<std::string> strings;
std::string::size_type pos = 0;
std::string::size_type prev = 0;
while ((pos = str.find(delimiter, prev)) != std::string::npos)
{
strings.push_back(str.substr(prev, pos - prev));
prev = pos + 1;
}
// To get the last substring (or only, if delimiter is not found)
strings.push_back(str.substr(prev));
return strings;
}
您可以看到该函数运行here的示例
然后只需使用该函数并将您的代码更改为:
#include <iostream>
#include <string.h>
#include <vector>
using namespace std;
int main(){
string filename;
string list = "hello.txt\n abc.txt\n check.txt\n"
cin >> filename;
vector<string> fileList = split_string(list, "\n");
bool found = false;
for(int i = 0; i<fileList.size(); i++){
if(fileList.at(i) == file){
found = true;
}
}
if(found){
cout << file << "exist in list";
} else {
cout << "file does not exist in list";
}
return 0;
}
显然,您需要在代码中的某个地方声明并实现函数
split_string
。可能在main
声明之前。关于c++ - 在以换行符分隔的字符串中查找特定文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40064423/