Showing posts with label STL. Show all posts
Showing posts with label STL. Show all posts

February 12, 2009

How To: STL String Case-insensitive Compare

This article is talking about how to do a case-insensitive compare for STL string and wstring, there're 2 ways to reach the goal.

Method #1: C Run-time Library - _stricmp() and _wcsicmp()

#include <string>

using namespace std;

string strUpperCase = "ABC";
string strLowerCase = "abc";
if(_stricmp(strUpperCase.c_str(), strLowerCase.c_str()) == 0)
// For wstring, use _wcsicmp() instead.
{
  // Do something you need
}


Method #2: STL Algorithm - transform()

#include <cctype>
#include <string>
#include <algorithm>

using namespace std;

// I make a helper function to compare string
bool CompareCaseInsensitive(string strFirst, string strSecond)
{
  // Convert both strings to upper case by transfrom() before compare.
  transform(strFirst.begin(), strFirst.end(), strFirst.begin(), toupper);
  transform(strSecond.begin(), strSecond.end(), strSecond.begin(), toupper);
  if(strFirst == strSecond) return true; else return false;
}

string strUpperCase = "ABC";
string strLowerCase = "abc";
if(CompareCaseInsensitive(strUpperCase, strLowerCase))
{
  // Do something you need
}


Reference in This Site:
How to convert STL string / wstring to upper / lower case?

Reference in MSDN:
_stricmp, _wcsicmp, _mbsicmp, _stricmp_l, _wcsicmp_l, _mbsicmp_l

October 04, 2008

How to convert STL string / wstring to upper / lower case?

This is the STL algorithm way, I think it is better than the itoa() way.

Sample Code:

#include <cctype>
#include <string>

#include <algorithm>


using namespace std;

// Convert string to lower case
string strTest = "I am a STL string";
transform(
  strTest.begin(), strTest.end(),
  strTest.begin(),
  tolower); // toupper for upper case

// Convert wstring to upper case
wstring wstrTest = L"I am a STL wstring";
transform(
  wstrTest.begin(), wstrTest.end(),
  wstrTest.begin(),
  towupper); // towlower for lower case

Reference in MSDN:

January 17, 2008

Notes for writing DLL in which use STL objects

You may experience an access violation when you access an STL object through a pointer or reference in a different DLL or EXE.

Root Cause:
Since the static data members in the executable images are not in sync, this action could result in an access violation or data may appear to be lost or corrupted.

Suggestion:
Avoid using STL object as the parameter or the return value of an exported DLL function.

MSDN Reference:

December 06, 2007

Convert Any Value Type to STL String by Stringstream

#include <sstream>

using namespace std;

int a = 1;
double b = 2.0;
float c = 3.0;
unsigned int d = 4;
long long f = 5;
__int64 g = 6;

wstringstream stream; (use stringstream for string)
wstring str;
stream << g; (this can be replaced by any value type)
stream >> str;