我想在句子列表中找到特定的字符串。每个句子都是用 \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;
}
有没有什么办法。我只想在列表中查找文件名
最佳答案
list.find
只会在字符串 list
中找到子字符串, 但是如果你想比较整个字符串直到找到 \n
, 你可以标记 list
并放入一些 vector 。
为此,您可以将字符串 list
在 std::istringstream
并制作一个std::vector<std::string>
使用 std::getline
摆脱它喜欢:
std::istringstream ss(list);
std::vector<std::string> tokens;
std::string temp;
while (std::getline(ss, temp)){
tokens.emplace_back(temp);
}
如果标记中有前导或尾随空格,您可以在将标记添加到 vector 之前修剪标记。有关修剪,请参阅 What's the best way to trim std::string? ,从那里找到适合您的修整解决方案。
然后,您可以使用 find
来自 <algorithm>
检查该 vector 中的完整字符串。
if (std::find(tokens.begin(), tokens.end(), filename) != tokens.end())
std::cout << "found" << std::endl;
关于c++ - 在由换行符分隔的字符串中查找特定文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40064423/