我是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
提前致谢。
答案 0 :(得分:1)
谢谢大家
我解决了下面的代码。
#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'
}
}
答案 1 :(得分:0)
假设您已经从文件中加载了字符串,在逗号上拆分并以可访问的方式存储它们,您正在寻找的替换调用应该是这样的:
size_t pos = input.find(toReplace); // toReplace = "text to replace"
if (pos != std::string::npos) {
input.replace(pos, toReplace.length(), shorterString); // shorterString = "new text"
} else {
// Your "text to replace" doesn't exist in input
}