Because I don't want to download an entire library for a single function (which I do understand, was made better than I made mine), I decided to implement my own string formatting function.
I am not very proud of it, as I find it pretty ugly and unreadable.
This is only a string formatter with string-only arguments.
Efficiency is not a concern for me.
#include<iostream>
#include<unordered_map>
#include<string>
using std::string;
string formatString(string format, const std::unordered_map<string, string>& args) {
string ret;
string::size_type bracketLoc;
while((bracketLoc = format.find_first_of('{')) != string::npos) {
// Handling the escape character.
if(bracketLoc > 0 && format[bracketLoc - 1] == '\\') {
ret += format.substr(0, bracketLoc + 1);
format = format.substr(bracketLoc + 1);
continue;
}
ret += format.substr(0, bracketLoc);
format = format.substr(bracketLoc + 1);
bracketLoc = format.find_first_of('}');
string arg = format.substr(0, bracketLoc);
format = format.substr(bracketLoc + 1);
auto it = args.find(arg);
if(it == args.end()) {
ret += "(nil)";
} else {
ret += it->second;
}
}
ret += format;
return ret;
}
int main() {
std::cout << formatString("Hello, {Name}! {WeatherType} weather, right?", {
{"Name", "Midnightas"},
{"Fruit", "Apple"}
});
return 0;
}
Compile with -std=c++11.
The above program will output Hello, Midnightas! (nil) weather, right?.
"This is %2 of %1\n", where%2is replaced with the second argument and%1is replaced with the first argument. Not sure if named arguments helps that much. \$\endgroup\$