• C

The conversion from char string to a wchar array: is it needed.

I wanted to do a strncmp() between 2 strings
The problem is one argument is unsigned char *string  and the other is a
wide char array.

I wanted to know what is a good solution in this case.
Do I need to use mbstowcs/mbsnrtowcs  to convert the char string to a wide char array and then use oone of wchar compare APIs

.Just casting the arguments won't do I presume since storage requirements
are different.

Also are there any portability issues/limitations in doing this.

Who is Participating?
You will need to convert the normal string to a wide string using mbrtowc(),
then compare the two wide strings using wcsncmp() as follows.

#include <wchar.h>

/* like strncmp() but compares a char string to a wchar string */
int mixedcmp(const char * str1, const wchar_t * wstr2, size_t n)
      // alloc a temp buffer to hold the wide version of str1
      wchar_t wstr1 = alloca((n+1)*sizeof(wchar_t));

      // get a wchar representation of str
      mbrtowc(wstr1, str1, n, NULL);

      // do the comparison and return the result
      return wcsncmp(wstr1, wstr2, n);

Kent OlsenData Warehouse Architect / DBACommented:
Hi sanjay_thakur,

You'll have to convert one of the string to be the same type as the other.  Comparing apples to apples, as it were.

The other choice is to find/write an API that compares strings of dissimilar type.  Not really a recommended solution.

Good Luck!
sanjay_thakurAuthor Commented:
Ok, I think the question boils down to
How do I convert an unsigned char array to wchar_t array in an
efficient manner using one of portable APIs.

There is no standard portable API's for converting from 8 bit ascii to unicode, but I am sure you will find some commercial solutions if you search for such.

But, if you know that the values in your 8 bit ascii are just ordinary US characters you can create a simple conversion yourself:

size_t i;
for( i = 0; i < char_array_length; ++i )
   wchar_array[i] = (wchar)char_array[i];

If there are requirements for handling other character sets and character values you just have to check the conversion tables at www.unicode.org

Unless you realy truly need a portable solution I would go for the solution from  brettmjohnson

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.