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

Find specific text in string delimited by newline characters

本文关键字:文本 字符串 换行符 分隔 查找      更新时间:2023-10-16

我想在一个句子列表中找到一个特定的字符串。每个句子都是用n分隔的一行。当到达换行符时,当前搜索应该停止并在下一行重新开始。

我的程序是:

#include <iostream>
#include <string.h>
using namespace std;
int main(){
    string filename;
    string list = "hello.txtn abc.txtn check.txtn"
    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进行标记并放入一些向量。

为此,您可以将字符串list放在std::istringstream中,并通过使用std::getline将其变为std::vector<std::string>,如:

std::istringstream ss(list);
std::vector<std::string> tokens;
std::string temp;
while (std::getline(ss, temp)){
    tokens.emplace_back(temp);
}

如果标记中有前导或尾随空格,则可以在将标记添加到向量之前修剪它们。关于精简,请参见精简std::string的最佳方法是什么?,从中找到适合你的修剪方案。

之后,您可以使用<algorithm>中的find来检查该向量中的完整字符串。

if (std::find(tokens.begin(), tokens.end(), filename) != tokens.end())
    std::cout << "found" << std::endl;

首先,我不会将文件列表保存在单个字符串中,但我会使用任何类型的列表或向量。然后,如果您需要将列表保存在字符串中(由于应用程序逻辑中的某种原因),我将在向量中分离字符串,然后循环遍历向量的元素,检查该元素是否正是搜索的元素。要拆分元素,我可以这样做:

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;
}

你可以在这里看到一个函数工作的例子

然后使用函数并将代码更改为:

#include <iostream>
#include <string.h>
#include <vector>
using namespace std;
int main(){
string filename;
string list = "hello.txtn abc.txtn check.txtn"
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声明之前