本人C++小白,初學STL,請問下面這道題怎么做?做好能附上完整代碼,感激不盡!
給定一個string,轉換為另一個string。每條規則由兩部分組成:一個可能出現在輸入檔案中的單詞和一個用來替換它的短語。表達的含義是,每當第一個單詞出現在輸入中,我們就將他替換為對應的短語。
單詞轉換檔案規則如下:
brb ---> be right back
k ---> okey?
y ---> why
r ---> are
u ---> you
pic ---> picture
thk ---> thanks!
18r ---> later
希望轉換的內容為:
where r u
y dont u send me a pic
k thk 18r
注 :要求使用map完成該題。
uj5u.com熱心網友回復:
用map把要替換的和替換后的關系建立起來,然后從檔案中讀出來,關鍵字進行替換uj5u.com熱心網友回復:
#include <stdio.h>
#include <string>
#include <map>
#include <iostream>
#include <vector>
static const char* arr[][2] = {
{"brb", "be right back"},
{"k", "okey?"},
{"y", "why"},
{"r", "are"},
{"u", "you"},
{"pic", "picture"},
{"thk", "thanks!"},
{"18r", "later"},
};
int split(const std::string& src, const std::string &pattern, std::vector<std::string>& vct) {
if (src.empty()) {
return 0;
}
int start = 0;
int idx = src.find_first_of(pattern, start);
while (idx != std::string::npos) {
if (start != idx) {
std::string tmp = src.substr(start, (idx - start));
vct.push_back(tmp);
}
start = idx + 1;
idx = src.find_first_of(pattern, start);
}
if (!src.substr(start).empty()) {
vct.push_back(src.substr(start));
}
return 0;
}
int main()
{
std::string strSrc = "where r u y dont u send me a pic k thk 18r";
std::map<std::string, std::string> mapping;
int size = sizeof(arr) / sizeof(*arr);
for (int i = 0; i < size; i++) {
mapping.insert(std::make_pair(arr[i][0], arr[i][1]));
}
std::vector<std::string> words;
split(strSrc, " ", words);
std::string result = "";
for (int i = 0; i < words.size(); i++) {
std::string& tmp = words[i];
std::map<std::string, std::string>::iterator it = mapping.find(tmp);
if (it != mapping.end()) {
tmp = it->second;
}
result += tmp;
if (i != (words.size() - 1)) {
result += " ";
}
}
std::cout << result;
return 0;
}
uj5u.com熱心網友回復:
結帖啊,給分啊轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/12620.html
標籤:C++ 語言
上一篇:c語言初學者的小問題
下一篇:VS怎樣用檔案夾管理工程
