Click here to Skip to main content
6,595,854 members and growing! (18,586 online)
Email Password   helpLost your password?
General Programming » String handling » General     Intermediate License: The Code Project Open License (CPOL)

String Format Library

By Shao Voon Wong

Another type-safe alternative to Boost's string format library.
C, VC6, VC7.1, VC8.0, Windows, Visual Studio, Dev
Posted:29 Nov 2006
Updated:23 Apr 2008
Views:33,696
Bookmarked:22 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
26 votes for this article.
Popularity: 4.44 Rating: 3.14 out of 5
9 votes, 40.9%
1

2
5 votes, 22.7%
3
4 votes, 18.2%
4
4 votes, 18.2%
5

Introduction

While I was writing this article, I saw that a fellow CP'ian, Ivo Beltchev, has already posted a typesafe string format library. The method I used in my library is quite similar to his. But my library is much simpler, and uses std::basic_string and C string functions to do the job instead of rolling out my own string routines, and doesn't use the Win32 API, but it doesn't support locale.

Here is an example of the usage:

using namespace strfmt;

std::wstring szHello = L"Hello";

std::wcout<< StrFormat( L"{0}, {0}, I am {1}", 
             szHello, 22.0 ) << std::endl;

The output is as below:

Hello, Hello, I am 22.000000

Source code

This is the function declaration, with a constant string and two arguments:

std::wstring strfmt::StrFormatW( 
    const wchar_t* fmt, 
    strfmt::BoxW box1, 
    strfmt::BoxW box2 );

Let us see its definition, which is surprisingly simple:

std::wstring strfmt::StrFormatW( 
    const wchar_t* fmt, 
    strfmt::BoxW box1, 
    strfmt::BoxW box2 )
{
    std::wstring wsfmtstr = fmt;

    std::vector<std::wstring> vs;
    vs.push_back( box1.ToString() );
    vs.push_back( box2.ToString() );

    return StrReplaceW( wsfmtstr, vs );
}

Let us see the class declaration of strfmt::BoxW:

class BoxW
{
public:
    BoxW( int i );

    BoxW( unsigned int ui );
    
    BoxW( const __int64& i64 );

    BoxW( const unsigned __int64& ui64 );

    BoxW( float f );

    BoxW( const double& d );

    BoxW( const std::string& s );
    
    BoxW( const std::wstring& ws );
    
    BoxW( const char* pc );

    BoxW( const wchar_t* pwc );
    
    BoxW( char c );

    BoxW( wchar_t wc );

    std::wstring& ToString() { return m_str; }

protected:
    std::wstring m_str;

};

The class consists of 12 non-default constructors, and a method, ToString(), which returns the internal string. The constructors merely convert the arguments to std::wstring and stores in m_str.

There is also an ASCII version of the class, which is used depending on whether _UNICODE is defined or not.

##ifdef _UNICODE
    #define StrFormat StrFormatW
    #define Hex HexW
    #define Oct OctW
    #define Bin BinW
    #define Sci SciW
    #define Flt FltW
#else
    #define StrFormat StrFormatA
    #define Hex HexA
    #define Oct OctA
    #define Bin BinA
    #define Sci SciA
    #define Flt FltA
#endif

In order to keep the library simple, the paradigm used is different from the .NET string format, the numbers formatting is kept outside.

std::wcout<< StrFormat( L"{0}, {1}, {2}", 
     Hex( 255 ), Sci( 22.0 ), Flt( 22.0, 3 ) ) << std::endl;

The output is as below:

ff, 2.200000e+001, 22.000

Supporting your own type

Just add a method (example, ToString()) to your custom class to return a std::string or std::wstring or any of the POD type supported by strfmt::BoxA and strfmt::BoxW.

using namespace strfmt;
    
MyClass myclass;

std::cout<< StrFormat( "{0} {1}", 
     myclass.ToString(), 22.0 ) << std::endl;

Conclusion

This string format library is designed from ground up, that it is so simple that any user can edit/add features himself/herself easily. If you compile the source code in Visual C++ 8 or Visual Studio 2005, it uses the new Safe C functions.

History

  • 29 November 2006 - First release in CodeProject.
  • 17 December 2006 - Corrected a typo in the code snippet, and solved buffer not allocating space for null terminator problems.
  • 23 April 2008 - Supports up to 10 POD parameters now.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Shao Voon Wong


Member
I am currently working as a software developer in a company specialized in 3D building visualization. I am extremely interested in optimizing techniques, for example, CPU SIMD instructions like the Intel SSE2, multi-threading techinques on multi-core/SMP processors and GPGPU languages like Brook+/CAL for ATI GPUs and nVidia's CUDA.

Like many Singaporeans, my hobbies include reading, karaoke, watching movies and anime, play games and jogging.

I wish I have more time to write articles for CodeProject since I have a few ideas(long overdue) to write about. And I always explain the working behind the code in my articles. I hope you like my articles on CodeProject!
Occupation: Software Developer
Location: Singapore Singapore

Other popular String handling articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 8 of 8 (Total in Forum: 8) (Refresh)FirstPrevNext
Generalpossibly a typo PinmemberLukas Rypacek2:40 13 Dec '06  
GeneralRe: possibly a typo PinmemberWong Shao Voon15:31 13 Dec '06  
GeneralRe: possibly a typo PinmemberLukas Rypacek0:25 14 Dec '06  
GeneralHi again, I was hoping you would help with this fstream problem Pinmembercomputerpublic9:47 9 Dec '06  
GeneralRe: Hi again, I was hoping you would help with this fstream problem PinmemberWong Shao Voon16:00 10 Dec '06  
GeneralRe: Hi again, I was hoping you would help with this fstream problem Pinmembercomputerpublic7:59 11 Dec '06  
Generalmultiple parameters Pinmembervoidbent22:46 5 Dec '06  
GeneralRe: multiple parameters PinmemberWong Shao Voon1:07 6 Dec '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 23 Apr 2008
Editor: Smitha Vijayan
Copyright 2006 by Shao Voon Wong
Everything else Copyright © CodeProject, 1999-2009
Web15 | Advertise on the Code Project