當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ wcscoll()用法及代碼示例

wcscoll()C++中的函數比較兩個以null終止的字符串。比較基於LC_COLLATE類別定義的當前語言環境。
此函數開始比較每個字符串的第一個字符。直到字符不同或直到到達表示字符串結尾的零寬度字符為止,它們才被視為相等。

用法:

int wcscoll( const wchar_t* wcs1, const wchar_t* wcs2 )

參數:該函數接受兩個強製性參數,如下所述:


  1. wcs1: 它是指向要比較的以null終止的寬字符串的指針。
  2. wcs2: 它是指向要比較的以null終止的寬字符串的指針。

返回值:該函數返回三個值,如下所示:

  1. 如果值指示兩個字符串相等,則為0。
  2. 如果wcs1中第一個不同的字符大於wcs2中相應的字符,則為正值。
  3. 如果在wcs1中不同的第一個字符小於在wcs2中對應的字符,則為負值。

以下示例程序旨在說明上述函數:
示例1:

// C++ program to illustrate 
// wcsoll() function 
#include <bits/stdc++.h> 
using namespace std; 
  
// function to compare two strings 
void comparetwo(const wchar_t* wcs1, const wchar_t* wcs2) 
{ 
    // pointer wcs1 points string 
    // pointer wcs2 points string_ 
    if (wcscoll(wcs1, wcs2) < 0) 
        wcout << wcs1 << L" precedes " << wcs2 << '\n'; 
  
    else if (wcscoll(wcs1, wcs2) > 0) 
        wcout << wcs2 << L" precedes " << wcs1 << '\n'; 
  
    else
        wcout << wcs2 << L" equals " << wcs1 << '\n'; 
} 
  
int main() 
{ 
    // initializing two strings 
    wchar_t string[] = L"article"; 
    wchar_t string_[] = L"everyone"; 
  
    // setting american locale 
    setlocale(LC_ALL, "en_US.utf8"); 
    wcout << L"In American : "; 
  
    // compare two strings with wcs1 and wcs2 
    comparetwo(string, string_); 
  
    // setting swedish locale 
    setlocale(LC_ALL, "sv_SE.utf8"); 
    wcout << L"In Swedish : "; 
    comparetwo(string, string_); 
  
    return 0; 
}
輸出:
In American : article precedes everyone
In Swedish : article precedes everyone

示例2:

// C++ program to illustrate 
// wcsoll() function 
#include <bits/stdc++.h> 
using namespace std; 
  
// function to compare two strings 
void comparetwo(const wchar_t* wcs1, const wchar_t* wcs2) 
{ 
    // pointer wcs1 points string 
    // pointer wcs2 points string_ 
    if (wcscoll(wcs1, wcs2) < 0) 
        wcout << wcs1 << L" precedes " << wcs2 << '\n'; 
    else if (wcscoll(wcs1, wcs2) > 0) 
        wcout << wcs2 << L" precedes " << wcs1 << '\n'; 
    else
        wcout << wcs2 << L" equals " << wcs1 << '\n'; 
} 
  
int main() 
{ 
    // initializing two strings 
    wchar_t string[] = L"geekforgeeks"; 
    wchar_t string_[] = L"gfg"; 
  
    // setting Czech locale 
    setlocale(LC_COLLATE, "cs_CZ.utf8"); 
    wcout << L"In Czech : "; 
  
    // compare two strings with wcs1 and wcs2 
    comparetwo(string, string_); 
  
    // setting american locale 
    setlocale(LC_COLLATE, "en_US.utf8"); 
    wcout << "In the American locale: "; 
    comparetwo(string, string_); 
  
    return 0; 
}
輸出:
In Czech : geekforgeeks precedes gfg
In the American locale: geekforgeeks precedes gfg


相關用法


注:本文由純淨天空篩選整理自AmanSrivastava1大神的英文原創作品 wcscoll() function in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。