C++ 从文本文件中查找不完整的字符串
C++ Finding an incomplete string from a text file
我有一个程序可以读取文本文件并从中解析信息,我正在尝试完成这样的任务:
一个包含大约 500 个字符数据的文本文件,在此数据中隐藏用户名如下:
this_just_some_random_data_in_the_file_hdfhehhr2342t543t3y3y
_please_don't_mind_about_me(username: "sara123452")reldgfhfh
2134242gt3gfd2342353ggf43t436tygrghrhtyj7i6789679jhkjhkuklll
问题是我们只需要从该文本文件中查找并写入sara123452
字符串。当然,用户名是未知的,并且没有固定的长度。
以下是我到目前为止设法做到的:
std::string Profile = "http://something.com/all_users/data.txt";
std::string FileName = "profileInfo.txt";
std::string Buffer, ProfileName;
std::ifstream FileReader;
DeleteUrlCacheEntryA(Profile .c_str());
URLDownloadToFileA(0, Profile .c_str(), FileName.c_str(), 0, 0);
FileReader.open(FileName);
if (FileReader.is_open())
{
std::ostringstream FileBuffer;
FileBuffer << FileReader.rdbuf();
Buffer= FileBuffer.str();
if (Buffer.find("(username: ") != std::string::npos) {
cout << "dont know how to continue" << endl;
}
FileReader.close();
DeleteFileA(FileName.c_str());
}
else {
}
cin.get();
那么如何获取用户名字符串并将其分配/复制到ProfileName
字符串?
我相信
您正在寻找的是类似于下面的代码 - 可能会进行细微调整以解释引用的用户名。这里的关键是要记住,你的 Buffer 变量是一个 std::string,一旦你有明确的开始和结束,你就可以使用子字符串。
std::size_t userNameStartIndex, userNameEndIndex
...
userNameStartIndex = Buffer.find("(username: ")) + 11;
if (userNameStartIndex != std::string::npos) {
userNameEndIndex = Buffer.find(")", userNameStartIndex);
if (userNameEndIndex != std::string::npos)
{
ProfileName = Buffer.substr(userNameStartIndex, userNameEndIndex - userNameStartIndex)
}
}
还有很多其他方法可以做到这一点,但我想这个方法会不那么痛苦。
#include <regex>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct Profile
{ // ...
string name;
};
int main(int argc, const char * argv[])
{
std::cout.sync_with_stdio(false); // optional
// read from file
string filename {"data1.txt"};
ifstream in {filename};
vector<Profile> profiles;
// tweaks this pattern in case you're not happy with it
regex pat {R"((username:s*"(.*?)"))"};
for (string line; getline(in,line); ) {
Profile p;
sregex_iterator first(cbegin(line), cend(line), pat);
const sregex_iterator last;
while (first != last) {
// By dereferencing a first, you get a smatch object.
// [1] gives you the matched sub-string:
p.name = (*first)[1]; // (*first)[1] = sara123452
profiles.push_back(p);
++first;
}
}
// Test
for (const auto& p : profiles)
cout << p.name << 'n';
}
相关文章:
- 使用正则表达式regex_search在字符串中查找字符串
- 按类型与字符串查找对象
- 使用C RTTI(内置)通过字符串查找功能指针
- 关于获取行和字符串查找函数的问题
- 字符串查找方法找不到第一字母
- C++ 字符串.查找()
- 遇到字符串::查找的问题
- 将一个数组作为子字符串查找到另一个数组中
- 字符串查找第一个非的 C++ 问题
- 如何将通配符与字符串::查找一起使用
- 字符串::查找问题 (C++)
- 性能标准::strstr vs. 标准::字符串::查找
- C++字符串::查找崩溃应用程序
- 使用字符串查找单词的正确方法是什么
- 如何在<string>没有 std::string 中介的情况下制作一个支持通过 C 字符串查找的集合?
- 使用C++根据行中的第一个字符串查找行(仅一个)
- Borland字符串::查找bug
- std::map如何通过字符串查找元素
- 字符串查找函数返回奇数
- 如何使用子字符串查找数字行的正确部分