#C++11 code, 386 characters# #include #include using namespace std;using =map<int,string>;using X=const char; format1(Xp,Xs,_ k=()){ r;while(*p!='{'){if(!*p||!s){returnp==*s?k:r;}if(p++!=s++)return r;}int v=0;while(++p!='}'){v=v10+(*p-48);}p++;if(k.find(v)!=k.end()){return format1((k[v]+p).c_str(),s,k);}while((r=format1(p,s,k)).empty()){k[v]+=*s++;if(!s){returnp==*s?k:r;}}return r;}
#include <string>
#include <map>
using namespace std;using _=map<int,string>;using X=const char;_ format1(X*p,X*s,_ k=_()){_ r;while(*p!='{'){if(!*p||!*s){return*p==*s?k:r;}if(*p++!=*s++)return r;}int v=0;while(*++p!='}'){v=v*10+(*p-48);}p++;if(k.find(v)!=k.end()){return format1((k[v]+p).c_str(),s,k);}while((r=format1(p,s,k)).empty()){k[v]+=*s++;if(!*s){return*p==*s?k:r;}}return r;}
for (auto v : format1("{1} {2}", "one two")){
cout << v.first << "=" << v.second << endl;
}
for (auto v : format1("{1} {2}", "one two")){
cout << v.first << "=" << v.second << endl;
}
example2Example 2:
auto v = format1("{1} {2}", "one two");
cout << v[1] << " and " << v[2] << endl;
auto v = format1("{1} {2}", "one two");
cout << v[1] << " and " << v[2] << endl;
The patterns are in decimal representation, inputs bigger than MAXINT
will overflow but it still works.
#include <string>
#include <map>
using namespace std;
using res = map<int,string>;
res format1(const char* p, const char* s, res k=res()){
res r; // intermediate result, empty until the end
// match until first '{'
while (*p != '{'){
if (!*p || !*s){
// exit case
return ((*p == *s) ? k : r); // == 0
}
if (*p++ != *s++)
return r;
}
// *p == '{'
int v = 0;
while(*++p != '}'){
v = v*10 + (*p - '0');
}
p++; // advance past '}'
// match back-references
if (k.find(v) != k.end()){
return format1((k[v]+p).c_str(), s, k);
}
// recursive search
while ( (r=format1(p, s, k)).empty() ){
k[v] += *s++;
if (!*s){
return *p == *s ? k : r;
}
}
return r;
}
#include <string>
#include <map>
using namespace std;
using res = map<int,string>;
res format1(const char* p, const char* s, res k=res()){
res r; // intermediate result, empty until the end
// match until first '{'
while (*p != '{'){
if (!*p || !*s){
// exit case
return ((*p == *s) ? k : r); // == 0
}
if (*p++ != *s++)
return r;
}
// *p == '{'
int v = 0;
while(*++p != '}'){
v = v*10 + (*p - '0');
}
p++; // advance past '}'
// match back-references
if (k.find(v) != k.end()){
return format1((k[v]+p).c_str(), s, k);
}
// recursive search
while ( (r=format1(p, s, k)).empty() ){
k[v] += *s++;
if (!*s){
return *p == *s ? k : r;
}
}
return r;
}