C++ String Code Snippets
Split a string
http://bytes.com/forum/thread221760.html
http://msdn.microsoft.com/en-us/library/2c8d19sb(VS.80).aspx
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”);
TCHAR szPath[MAX_PATH];
_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
Syntax
wchar_t * _itow(int value, wchar_t (&str)[size], int radix ); |
|
value |
Number to be converted. |
str |
String result. |
Radix |
which must be in the range 2–36 |
Sample:
char buffer[65];
int r;
_itoa(137.5, buffer, 10);