Skip to content

Instantly share code, notes, and snippets.

@ZwodahS
Last active August 29, 2015 14:06
Show Gist options
  • Save ZwodahS/35f342c1a0fce90c928b to your computer and use it in GitHub Desktop.
Save ZwodahS/35f342c1a0fce90c928b to your computer and use it in GitHub Desktop.
C++ simple string formating
/*
* DO WHAT THE F*** YOU WANT TO PUBLIC LICENSE
* Version 2, December 2004
*
* Copyright (C) 2013- ZwodahS(ericnjf@gmail.com)
* zwodahs.github.io
*
* Everyone is permitted to copy and distribute verbatim or modified
* copies of this license document, and changing it is allowed as long
* as the name is changed.
*
* DO WHAT THE F*** YOU WANT TO PUBLIC LICENSE
* TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
*
* 0. You just DO WHAT THE F*** YOU WANT TO.
*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details.
*
* Or just consider this as public domain.
*/
/**
* Code extracted from zframework at github.com/ZwodahS/zframework,
*/
/**
* Usage :
*
* (format("Hello %s") % world).str
* (format("%i + %i is %i) % 3 % 5 % 8).str
* (format("Hello Wo%cld) % 'r').str
*
* This is unoptimized, and boost should be used if possible.
* Just throw this into your project, put it into a namespace if you, or modify if you see fit.
* Let me know if you implement the operator for other type so I can update this gist.
*
* The most updated version will be in my personal codebase in the link above, but I will update this
* as much as possible.
*/
//////////////////// Header
class Format
{
public:
Format(const std::string& str);
Format& operator%(int i);
Format& operator%(char c);
Format& operator%(const std::string& str);
std::string str;
};
Format format(const std::string& str);
//////////////////// Source
std::string& replaceString(std::string& newString, const std::string& searchString, const std::string& replaceString)
{
auto index = newString.find(searchString);
if(index != std::string::npos)
{
newString.replace(index, searchString.size(), replaceString);
}
return newString;
}
Format::Format(const std::string& str)
: str(str)
{
}
Format format(const std::string& str)
{
return Format(str);
}
Format& Format::operator%(int i)
{
std::string s = intToString(i);
replaceString(str, "%i", s);
return *this;
}
Format& Format::operator%(char c)
{
std::string s = charToString(c);
replaceString(str, "%c", s);
return *this;
}
Format& Format::operator%(const std::string& s)
{
replaceString(str, "%s", s);
return *this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment