C++ String Code Snippets

0.00 avg. rating (0% score) - 0 votes

Split a string




We are going to use wcstok to split string into tokens using separators. This function modifies the original string. Therefore, the original string cannot be declared as below:

wchar_t *testStr = L”Hello world”;

This will cause Access Violation when wcstok attempts to modify the string since the pointer returned by L”” is a constant pointer. We must declare a string buffer and copy a string constant into that buffer as followed:

wchar_t *testStr = new wchar_t[100];

LPTSTR testStr2 = _T(“Hello World;Hello World 1;Hello World 2;Hello World 3;Hello World 4″);

wcscpy(testStr, testStr2);

const wchar_t *seps = _T(“;”);

Or alternatively:

WCHAR testStr2[] = _T(“Hello World;Hello World 1;Hello World 2;Hello World 3;Hello World 4″);

const WCHAR seps = ‘;';

The rest is straightforward:

// Establish string and get the first token:

wchar_t* token = wcstok(testStr, seps);

// print the first and the next tokens, if any

while (token != NULL)


printf(“%Sn”, token);

token = wcstok(NULL, seps);


Concatenate strings & compare strings:

//Result: szPath contains ‘C:Program Filesapp.exe’

LPCTSTR pszInstallDir = L”C:\Program Files”;

const wchar_t *appExecutable = _T(“app.exe”);


_tcscpy(szPath, pszInstallDir);

_tcscat(szPath, _T(“\”));

_tcscat(szPath, appExecutable);

//returns TRUE since szPath contains appExecutable

BOOL contains = _tcsstr(szPath, appExecutable);


Load a string from resource:

LPWSTR str = new wchar_t[MAX_PATH];

LoadString(GetModuleHandle(IMAGENAME), IDS_str, str, MAX_PATH);

IMAGENAME: name of the executabe/dll owning the resource file

IDS_str: name of the resource

Str: the resource value

ANSI string to and from wide string

char* ch = “Hello”;

wchar_t *wa = new wchar_t[50];

mbstowcs(wa, ch, 50);

wchar_t *wa = L”Hello”;

char* ch = new char[MAX_PATH];

wcstombs(ch, wa, MAX_PATH);

String to Integer and vice versa

In C:

char *a = “137.5”;

float b = 0;

sscanf(a, “%f”, &b);

printf(“b = %f”, b);

In C++:

std::string a = “137.5”;

std::istringstream b(a);

float f;

b >> f;

Using _itoa/itow for integer to string and _atoi64/_itoa64 for string to integer


wchar_t * _itow(int value, wchar_t (&str)[size], int radix );


Number to be converted.


String result.


which must be in the range 2–36


char buffer[65];

int r;

_itoa(137.5, buffer, 10);

0.00 avg. rating (0% score) - 0 votes


A tough developer who likes to work on just about anything, from software development to electronics, and share his knowledge with the rest of the world.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>