Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

A CStringT-like STL string class

0.00/5 (No votes)
18 Apr 2006 1  
A string class based on STL and that can be used like the CStringT in MFC.

Introduction

In the STL library, there is a class which is called std::string, which can do a lot of outstanding extra work without any extra code. However, there's no Format() method like in MFC in its methods, and I started to write a class which could do this: job:String.

The class String can format string as if you've called the Format() method in MFC, but we do not need MFC indeed. Thus we can just use String instead of CStringT. The following member functions are supplied in this class:

  • operators (=, +, +=, CHAR(), c_str(), !=, ==, <=, >=, <, >, [])
  • ToLower(), ToUpper()
  • Mid(), Left(), Right()
  • Compare(), CompareNoCase()
  • Reverse(), Replace(), Remove(), Insert(), Delete(), Empty()
  • TrimLeft(), TrimRight()
  • Find(), FindOneOf(), ReverseFind()
  • Format()
  • GetBuffer(), GetBufferSetLength(), ReleaseBuffer(), GetLength()
  • IsEmpty()
  • GetAt(), SetAt()

How-to use this class

The following example shows how we can use this class:

#include <string>

#include "string.hpp"


String s1;
s1 = "abc";
s1 += std::string("123") + "123";
String s2 = s1.Reverse(); 
s2.Format("%d,this,%c",123,'c');
char* ptr_data = s2.CHAR();
...

Lack of code

I didn't add some platform-related functions in this class, because I want to use it as an platform independent class. The following list shows the CStringT member functions which were used in MFC's CStringT but not included in the class String:

  • AllocSysString()
  • SetSysString()
  • LoadString()
  • AnsiToOem()
  • OemToAnsi()

Conclusion

This article shows just a small usage of the code I wrote. You can use it wherever you use your CStringT in MFC.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here