SimpleLib

String Classes and Functions

SimpleLib's string class is a template class designed for managing NULL terminated strings.

  • Implemented using a single string member variable so can be passed to printf style functions. (except with gcc)
  • Supports "copy on write" for efficient passing as parameter's and return values.
  • Supports ANSI and Unicode strings.

Declaring a string variable:

CString<char> strAnsiString;
CString<wchar_t> strUnicodeString;

There are also typedefs for these most common string types:

CAnsiString strAnsiString;
CUniString strUnicodeString;

Constructing an initialised string:

CUniString str(L"Hello World");

CString includes an operator to T* for easy passing of CString's to functions expecting const T* pointers:

CAnsiString strFileName("test.txt");
FILE* p=fopen(strFileName, "rt");

To get a pointer to a writeable character buffer, use GetBuffer specifying the size of the required buffer. You can then optionally call FreeExtra to shrink the buffer down to the size of the contained string:

CAnsiString strModulePath;
GetModuleFileName(NULL, strModulePath.GetBuffer(MAX_PATH), MAX_PATH);
strModulePath.FreeExtra();

Get the length of the contained string in characters using GetLength:

CAnsiString str("Hello World");
printf("'%s' is %i characters in length\n", str, str.GetLength());

Check for empty strings with IsEmpty:

if (str.IsEmpty())
{
	...
}

Append a string with the Append function or the += operator.

CAnsiString str("Hello");<br />str+=" World";

Other manipulation functions are Replace, Insert and Delete.

Note when using +=, Append, Replace and Insert, CString uses a buffer doubling algorithm to grow the buffer effeciently (for speed) and is therefore excellent for building up large strings. You might want to use FreeExtra when finished building the string to release any unused memory.

String Functions

The Format function provides printf style formatting, returning the formatted string as a CString:

MessageBox(NULL, Format("Hello %s", m_strUserName), "My App", MB_OK);

Left, Mid and Right return substrings:

// Returns "Hello"
Left("Hello World", 5);

// Returns "World"
Right("Hello World", 5);

// Returns "ello"
Mid("Hello World", 1, 4);

Compare and CompareI perform case-sensitive and case-insensitive comparisons:

if (Compare("Hello World", "Goodbye World")==0)
{
	...
}

Note: although these Compare functions map directly to C runtime functions, there encapsulation as a templatized functions makes them easier to use from other template classes.