C庫 - towctrans() 函式



C 的wctypetowctrans() 函式用於根據指定的轉換描述符轉換寬字元。

“轉換描述符”是一個定義特定字元轉換型別的物件,例如將字元轉換為大寫或小寫。這些描述符被諸如“towctrans”之類的函式用於對寬字元執行所需的轉換。

語法

以下是 towctrans() 函式的C庫語法:

wint_t towctrans( wint_t wc, wctrans_t desc );

引數

此函式接受一個引數:

  • wc − 它是需要轉換的型別為'wint_t'的寬字元。

  • desc − 它是型別為wctrans_t的描述符。該描述符通常使用wctrans函式獲得。

返回值

如果wc(寬字元)具有“desc”指定的屬性,則此函式返回非零值;否則返回零。

示例1

以下示例演示了使用 towctrans() 將寬字元轉換為其大寫等效項。

#include <wctype.h>
#include <wchar.h>
#include <stdio.h>

int main() {
   // The wide character to be transformed
   wint_t wc = L'a';
   // Get the transformation descriptor for uppercase conversion
   wctrans_t to_upper = wctrans("toupper");  

   if (to_upper) {
      wint_t res= towctrans(wc, to_upper);
      if (res != WEOF) {
         wprintf(L"Transformed character: %lc\n", res);
      } else {
         wprintf(L"Transformation failed.\n");
      }
   } else {
       wprintf(L"Invalid transformation descriptor.\n");
   }

   return 0;
}

輸出

以下是輸出:

Transformed character: A

示例2

讓我們建立另一個示例,我們使用 towctrans() 建立desc(描述符)來將小寫字元轉換為大寫,反之亦然。

#include <wctype.h>
#include <wchar.h>
#include <stdio.h>

int main() 
{ 
   wchar_t str[] = L"Tutorialspoint India"; 
   wprintf(L"Before transformation \n");
   wprintf(L"%ls \n", str);
   for (size_t i = 0; i < wcslen(str); i++) {
      // check if it is lowercase 
      if (iswctype(str[i], wctype("lower"))) {
	     // transform character to uppercase 
		 str[i] = towctrans(str[i], wctrans("toupper"));
      }			
      // checks if it is uppercase 
      else if (iswctype(str[i], wctype("upper"))){
	    // transform character to uppercase 
		str[i] = towctrans(str[i], wctrans("tolower")); 
      }			
   } 
   wprintf(L"After transformation \n");
   wprintf(L"%ls", str); 
   return 0; 
} 

輸出

以下是輸出:

Before transformation 
Tutorialspoint India 
After transformation 
tUTORIALSPOINT iNDIA

示例3

下面的示例使用 towctrans() 建立desc(描述符)來將大寫字元轉換為小寫,反之亦然。

#include <wctype.h>
#include <wchar.h>
#include <stdio.h>

int main() 
{ 
   wchar_t str[] = L"Hello, Hyderabad visit Tutorialspoint 500081"; 
   wprintf(L"Original string: %ls \n", str);

   for (size_t i = 0; i < wcslen(str); i++) {
      // If the character is lowercase, transform it to uppercase
      if (iswctype(str[i], wctype("lower"))) {
         str[i] = towctrans(str[i], wctrans("toupper"));
      }
      // If the character is uppercase, transform it to lowercase
      else if (iswctype(str[i], wctype("upper"))) {
         str[i] = towctrans(str[i], wctrans("tolower"));
      }
   }

   wprintf(L"Transformed string: %ls \n", str);
   return 0; 
}

輸出

以下是輸出:

Original string: Hello, Hyderabad visit Tutorialspoint 500081 
Transformed string: hELLO, hYDERABAD VISIT tUTORIALSPOINT 500081 
c_library_wctype_h.htm
廣告
© . All rights reserved.