This kata is the first of a sequence of four about “Squared Strings”.
You are given a string of n lines, each substring being n characters long: For example:
s = "abcd\nefgh\nijkl\nmnop"
We will study some transformations of this square of strings.
Vertical mirror: vert_mirror (or vertMirror or vert-mirror)
vert_mirror(s) => "dcba\nhgfe\nlkji\nponm"
Horizontal mirror: hor_mirror (or horMirror or hor-mirror)
hor_mirror(s) => "mnop\nijkl\nefgh\nabcd"
or printed:
vertical mirror |horizontal mirror
abcd --> dcba |abcd --> mnop
efgh hgfe |efgh ijkl
ijkl lkji |ijkl efgh
mnop ponm |mnop abcd
Task:
Write these two functions
and
high-order function oper(fct, s) where
fct is the function of one variable f to apply to the string s (fct will be one of vertMirror, horMirror)
Examples:
s = "abcd\nefgh\nijkl\nmnop"
oper(vert_mirror, s) => "dcba\nhgfe\nlkji\nponm"
oper(hor_mirror, s) => "mnop\nijkl\nefgh\nabcd"
Note:
The form of the parameter fct in oper changes according to the language. You can see each form according to the language in “Sample Tests”.
Bash Note:
The input strings are separated by , instead of \n. The output strings should be separated by \r instead of \n. See “Sample Tests”.
要点
- 利用
stringstream >>
时以空白为分割符切割字符串. - 用反向迭代器来反转字符串.
- 用压栈和出栈来实现水平镜像.
#include <sstream>
#include <string>
#include <iostream>
#include <cmath>
#include <stack>
class Opstrings
{
public:
static std::string vertMirror(const std::string &strng){
std::stringstream ss{strng};
std::string tmp{};
std::string res{""};
while(ss>> tmp) {
if(res!= "") res.append("\n");
res.append(std::string(tmp.rbegin() , tmp.rend()));
}
return res;
}
static std::string horMirror(const std::string &strng){
std::stack<std::string> lines{};
std::stringstream ss{strng};
std::string tmp{};
std::string res{""};
while(ss >> tmp) {
if(!lines.empty()) lines.push("\n");
lines.push(tmp);
}
while(!lines.empty()){
res.append(lines.top()) ;
lines.pop();
}
return res;
}
// your high order function oper
//... oper(...);
static std::string oper(std::string (*func)(const std::string& ), const std::string &s){
return func(s);
}
};