【问题标题】:iterating each word in a line(string) c++迭代一行中的每个单词(字符串)c ++
【发布时间】:2017-06-18 00:21:30
【问题描述】:

所以基本上我想要实现的是我有一个文本文件,我必须找到一个特定的单词以及位置(行的位置和单词在该行的位置)。如何使用 C++ 的基本知识来实现​​它...我是新手,还没有研究过矢量等。感谢您的帮助

fstream x;
x.open("file.txt);
while(getline(x,str)) {
    //extract word from str and save in str1
    if(reqWord == str1)
        print("match found");
}`

【问题讨论】:

  • 您遇到了哪些问题?匹配单词?确定行号?确定行中的位置?我会逐行阅读文本,同时记录阅读的行数。使用string::find() 检查每一行,它还返回字符串开始的位置。
  • 查找行中的单词以及行中的位置...嗯,行位置很容易找出...但是找到单词在行中的位置

标签: c++ string file


【解决方案1】:

这是一种高级技巧,但我建议您尝试stringstream

std::stringstream ss;
ss << str;

while(ss >> str1)
  ...

【讨论】:

    【解决方案2】:

    您可以使用find 来搜索特定出现的搜索词。它将返回第一次出现的位置,否则 npos 如果它不在当前行上。 请在下面找到一个工作示例:

    已编辑 - 使用带有单词边界的正则表达式

    #include <iostream>
    #include <fstream>
    #include <regex>
    
    int main() {
    
        std::cout << "Please input the file path" << std::endl;
    
        std::string path;
    
        std::cin >> path;
    
        std::ifstream file(path.c_str());
    
        if (file.is_open()) {
            std::string search;
    
            std::cout << "Please input the search term" << std::endl;
            std::cin >> search;
    
            std::regex rx("\\b" + search + "\\b");
    
            int line_no = 1;
    
            for (std::string line; std::getline(file, line); ++line_no) {
                std::smatch m;
    
                if (std::regex_search(line, m, rx)) {
                    std::cout << "match 1: " << m.str() << '\n';
                    std::cout << "Word " << search << " found at line: " << line_no << " position: " << m.position() + 1
                              << std::endl;
                    break;
                }
            }
        } else {
            std::cerr << "File could not be opened." << std::endl;
            return 1;
        }
    
        return 0;
    }
    

    【讨论】:

    • 非常感谢 :)
    • 这不会只找到 OP 请求的单词,而是任何子字符串匹配。
    • 我已编辑答案以解决@zett42 指出的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多