示例

下面的例子使用 wcscoll 子例程比较两个宽字符字符串,比较依据是两者的整理权重。

#include  <stdio.h>
#include  <string.h>
#include  <locale.h>
#include  <stdlib.h>
 
extern  int  errno;
 
main()
{
    wchar_t  *pwcs1, *pwcs2;
    size_t   n;
 
    (void)setlocale(LC_ALL,  "");
    
    /*    set it to zero for checking errors on wcscoll    */
    errno  =  0;
    /*
    **    Let pwcs1 and pwcs2 be two wide character strings to
    **    compare.
    */
    n  =  wcscoll(pwcs1, pwcs2);
        /*
        **    If errno is set then it indicates some
        **    collation error.
        */
    if(errno  !=  0){
        /*  error has occurred... handle error ...*/
    }
}

下面的例子使用 wcsxfrm 子例程根据整理权重比较两个宽字符字符串。

注: 确定已转换字符串的大小 N (其中 N 是数字) ,在使用 世界安全与合作组织 /world confederation 子例程时,可以通过下列其中一种方式来完成:
  • 对于宽字符字符串中的每一个字符,可能的整理值的字节数不可能超过 COLL_WEIGHTS_MAX * sizeof(wchar_t) 值。 乘以宽字符码数目后得到的这个值,给出了所需的缓冲区长度。 给这个缓冲区长度再加 1,这一位是提供给起终止作用的宽字符 null。 这一策略可能降低性能。
  • 估计所需的字节长度。 如果先前获得的值不够,可以再增加。 这可能不能满足所有的字符串,但却能获得最佳性能。
  • 调用 wcsxfrm 子例程两次:第一次查找 n 的值,第二次使用这个 n 值来转换字符串。 这一策略降低了性能,因为调用了两次 wcsxfrm 子例程。 但是,这一方法可以得到存储被转换字符串所需缓冲区长度的精确值。

选择哪个方法取决于程序中用到的字符串的特征以及程序的性能目标。

#include  <stdio.h>
#include  <string.h>
#include  <locale.h>
#include  <stdlib.h>
 
main()
{
    wchar_t  *pwcs1, *pwcs2, *pwcs3, *pwcs4;
    size_t   n, retval;
  
    (void)setlocale(LC_ALL, "");
    /*
    **  Let the string pointed to by pwcs1 and pwcs3 be the
    **  wide character arrays to store the transformed wide
    **  character strings. Let the strings pointed to by pwcs2
    **  and pwcs4 be the wide character strings to compare based
    **  on the collation values of the wide characters in these
    **  strings.
    **  Let n be large enough (say,BUFSIZ) to transform the two
    **  wide character strings specified by pwcs2 and pwcs4.
    **
    **  Note:
    **  In practice, it is best to call wcsxfrm if the wide
    **  character string is to be compared several times to
    **  different wide character strings.
    */
 
    do {
        retval = wcsxfrm(pwcs1, pwcs2, n);
        if(retval == (size_t)-1){
            /*  error has occurred.  */
            /*  Process the error if needed  */
            break;
        }
 
        if(retval >= n ){
        /*
        ** Increase the value of n and use a bigger buffer pwcs1.
        */
        }
    }while (retval >= n);
 
    do {
        retval = wcsxfrm(pwcs3, pwcs4, n);
        if (retval == (size_t)-1){
            /*  error has occurred.  */
            /*  Process the error if needed  */
            break;
 
        if(retval >= n){
        /*Increase the value of n and use a bigger buffer pwcs3.*/
        }
    }while (retval >= n);
    retval = wcscmp(pwcs1, pwcs3);
    /*  retval has the result  */
}