65.9K
CodeProject is changing. Read more.
Home

A CStringT-like STL string class

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.63/5 (11 votes)

Apr 18, 2006

CPOL

1 min read

viewsIcon

44151

downloadIcon

422

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.