Advertisement
zhangsongcui

StringFormat

Jul 27th, 2011
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. #include <string>
  2. #include <sstream>
  3. #include <iostream>
  4. #include <cstdlib>
  5. //TODO: When the std::regex is implimented, use it
  6. //#include <regex>
  7. #include <boost/regex.hpp>
  8.  
  9. using namespace std;
  10. //TODO: When the std::regex is implimented, remove this
  11. using namespace boost;
  12.  
  13. class StringFormat
  14. {
  15. public:
  16.     StringFormat(const string& rhs): fmtString(rhs), reg(R"(\{(\d+?)\})"), index() {}
  17.     StringFormat(string&& rhs): fmtString(rhs), reg(R"(\{(\d+?)\})"), index() {}
  18.  
  19.     template <typename Object>
  20.     void Format(const Object& obj)
  21.     {
  22.         string::const_iterator start=fmtString.begin(), end=fmtString.end();
  23.         smatch what;
  24.         while(regex_search(start, end, what, reg))
  25.         {
  26.             if (atoi(string(what[1].first, what[1].second).c_str()) == index)
  27.             {
  28.                 fmtString.replace(what[0].first-fmtString.begin(), what[0].second-what[0].first, toString(obj));
  29.                 break;
  30.             }
  31.             start = what[0].second;
  32.         }
  33.         if (start == end)
  34.         {
  35.             throw invalid_argument("You are full of bullshit");
  36.         }
  37.         ++index;
  38.     }
  39.  
  40.     template <typename Object, typename... Args>
  41.     void Format(const Object& obj, Args... args)
  42.     {
  43.         Format(obj);
  44.         Format(args...);
  45.     }
  46.  
  47.     string getResult()
  48.     {
  49.         if (regex_search(fmtString, reg))
  50.             throw invalid_argument("You are full of bullshit");
  51.         return fmtString;
  52.     }
  53.  
  54. private:
  55.     string fmtString;
  56.     regex reg;
  57.     int index;
  58.  
  59. private:
  60.     template <typename Type>
  61.     static string toString(const Type& rhs)
  62.     {
  63.         ostringstream oss;
  64.         oss << rhs;
  65.         return oss.str();
  66.     }
  67. };
  68.  
  69.  
  70. int main()
  71. {
  72.     StringFormat sf("{1}+{0}={2}");
  73.     sf.Format(1, 2, 1+2);
  74.     cout << sf.getResult();
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement