我是C ++的新手。C++函数的工作方式如下。
查找文件:

POST OFFICE,PO
SUITE ACCESS ROOM, SAR
SUITE,STE
STREET,ST
NEW YORK,NY
POST,PST
LONG LINE STREET,LLS


将有一个c ++函数,该函数应具有一个像“ ARIJIT, 192 POST OFFICE, SUITE”这样的参数,并且它将给出类似“ ARIJIT, 192 PO, STE”的输出。它将使用一个静态查找文件,如上层内容。

我做了下面的代码结构,但没有找到前进的方向。

#include <iostream>
#include <fstream>
#include <string>
int main()
{
    char * processAddress (char *input );
    char *input = "ARIJIT, 192 POST OFFICE, SUITE";
    char *output = processAddress(input);
    std::cout << output;
    return 0;
}

char * processAddress (char *input ) {
    char *output = input;

    std::ifstream file("LookUp.csv");
    std::string str;
    while (std::getline(file, str))
    {
        std:: cout << str << '\n';
    }
    return output;
}


我面临的问题

1. How to map look up file

2. Find and Replace


提前致谢。

最佳答案

谢谢你们

我下面解决的是代码。

#include <iostream>
#include <fstream>
#include <string>
#include <map>
int main()
{
    std::string processAddress (std:: string input);
    std::string input = "ARIJIT, 192 POST OFFICE, SUITE";
    std::string output = processAddress(input);
    std::cout << output << "\n";
    return 0;
}

std::string processAddress (std:: string input) {
    void replaceAll(std::string& str, const std::string& from, const std::string& to);
    std::ifstream file("LookUp.csv");
    std::string str;
    typedef std::map<std::string, std::string> MyMap;
    MyMap my_map;
    while (std::getline(file, str))
    {
        std::string delimiter = ",";
        std::string token1 = str.substr(0, str.find(delimiter));
        std::string token2 = str.substr(token1.length()+1, str.find(delimiter));
        my_map[token1] = token2;
    }
    // Map Enumeration
    for( MyMap::const_iterator it = my_map.end(); it != my_map.begin(); --it )
    {
        std::string key = it->first;
        std::string value = it->second;
        // find and replace
        replaceAll(input, key, value);
    }

    std::string output = input ;
    return output;
}
bool replace(std::string& str, const std::string& from, const std::string& to) {
    size_t start_pos = str.find(from);
    if(start_pos == std::string::npos)
        return false;
    str.replace(start_pos, from.length(), to);
    return true;
}
void replaceAll(std::string& str, const std::string& from, const std::string& to) {
    if(from.empty())
        return;
    size_t start_pos = 0;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
    }
}

关于c++ - C++字符串匹配和使用查找文件替换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21300759/

10-11 14:44