1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
#include <iostream>
#include <cstdlib>
#include <algorithm>
// convert narrow character string (NTMBS, array of size SZ)
// to sequence of wide characters. return pointer to statically allocated buffer
// so the function is not thread-safe; use the result immediately (before the next call)
template < std::size_t SZ > const wchar_t* to_wcs( const char (&mbs)[SZ] )
{
static wchar_t wstr[SZ] ;
std::mbstowcs( wstr, mbs, SZ ) ;
return wstr ;
}
// compare narrow character string (NTMBS) with wide character string
// of wcs_sz characters ie. wcs_sz*sizeof(wchar_t) bytes
// the wide character string need not be null terminated
// semantics are similar to that of std::strncmp
template < std::size_t SZ >
int mbs_wcs_ncmp( const char (&mbs)[SZ], const wchar_t* wcs, std::size_t wcs_sz )
{ return std::wcsncmp( to_wcs(mbs), wcs, std::min( SZ, wcs_sz ) ) ; }
// locate the logical equivalent of wide character string of wcs_sz characters inside
// a narrow character string (NTMBS). the wide character string need not be null terminated.
// other than that, the semantics are similar to that of std::strstr
template < std::size_t SZ >
const char* mbs_wcs_nstr( const char (&mbs)[SZ], const wchar_t* wcs, std::size_t wcs_sz )
{
const wchar_t* wstr = to_wcs(mbs) ;
const auto p = std::search( wstr, wstr+SZ , wcs, wcs + std::min(SZ,wcs_sz) ) ;
return p == (wstr+SZ) ? nullptr : mbs + (p-wstr) ;
}
// non-const overload for the above
template < std::size_t SZ >
char* mbs_wcs_nstr( char (&mbs)[SZ], const wchar_t* wcs, std::size_t wcs_sz )
{ return (char*) mbs_wcs_nstr( (const char (&)[SZ])mbs, wcs, wcs_sz ) ; }
int main()
{
const char cstr[] = "abcdefghijkl" ;
const wchar_t wstr[] = L"abcdefghijkl" ;
std::cout << mbs_wcs_ncmp( cstr, wstr, 10 ) << '\n' ; // 0
const wchar_t wstr2[] = L"ghijkl" ;
std::cout << mbs_wcs_ncmp( cstr, wstr2, 5 ) << '\n' // negative (typical)
<< mbs_wcs_nstr( cstr, wstr2, 4 ) << '\n' ; // ghijkl
const wchar_t wstr3[] = L"MNOP" ;
std::cout << mbs_wcs_ncmp( cstr, wstr3, 4 ) << '\n' // positive (typical)
<< (const void*) mbs_wcs_nstr( cstr, wstr3, 4 ) << '\n' ; // nullptr (not found)
}
|