c++ - 在由换行符分隔的字符串中查找特定文本

标签 c++ string

我想在句子列表中找到特定的字符串。每个句子都是用 \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 。

为此,您可以将字符串 liststd::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/

相关文章:

c++ - 如何使 OpenCV 跟踪类从基类派生?

c++ - 我怎样才能让它更快? (C/C++) OpenCV

python - 比较字符串: file and lists

c# - 在 C# 函数中键入 'string' 作为参数

javascript - 用感叹号替换问号,反之亦然

c++ - 复合赋值的左边表达式是一个未初始化的值。计算值也将是垃圾

c++ - 从 Lua 修改 main() 中的 C++ 数组,无需额外分配

c++ - 使用 future wait_for 时无法检查成员变量,但如果我在线程中休眠,它会起作用

python - 如何按数字部分的升序对字符串列表进行排序

javascript - 在替换之前获取子字符串的位置