查找由换行符分隔的字符串中的特定文本
Find specific text in string delimited by newline characters
我想在一个句子列表中找到一个特定的字符串。每个句子都是用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
声明之前
相关文章:
- 在 C++ 中从 8 位 ASCII 字符创建 7 位 ASCII 文本字符串
- cin>>gender 和 cin>>*gender ( c 样式文本字符串)有什么区别
- 是否可以动态检查文本字符串是否是 C++ 中给定类的成员?
- 用Zlib解压缩文本字符串
- 将文本字符串作为常量字符 * 参数传递会导致代码分析器错误
- 来自文本字符串或某种其他机制的代码类自动生成器
- 函数读取最大和min int值,并用文本字符串返回
- 模板代码和文本字符串
- 声明具有常量引用与常量变量的常量文本字符串
- 加密给定的文本字符串-Caesar Cipher
- 如何使用键盘输入和sf ::文本在SFML中添加一种文本框以显示文本字符串
- 在C++代码中,如何让用户在2个文本字符串之间输入一个数字
- 如何将文本从一个文件复制到另一个文件,然后将文本字符串的第一个字母转换为大写
- 从文本字符串推断类型
- 跟踪内存中的文本字符串
- 将字符串变量与整数和文本字符串连接起来的 C++ 字符串流
- 将 char 数组分配给文本字符串 - C++
- 如何修复将文本字符串附加到 C 字符串的错误
- 使用C++读取不同长度的多个文本字符串
- 在C++中创建原始文本字符串,类似于 C# 的"@ string"