C 库 - towupper() 函数

❮ C 标准库 - <wctype.h>


C wctype 库中的 towupper() 函数用于将给定的宽字符转换为大写(如果可能)。

此函数可用于不区分大小写的比较、文本规范化或用户输入处理。

语法

以下是 towupper() 函数的 C 库语法 -

wint_t towupper( wint_t wc );

参数

此函数接受单个参数 -

  • wc - 它是一个需要转换为大写字母的"wint_t"类型的宽字符。

返回值

如果宽字符已转换为大写字母,则此函数返回大写字母,否则返回不变的字符(如果宽字符已经是大写字母或不是字母字符)。

示例 1

以下是演示 towupper() 函数用法的基本 C 语言示例。

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

int main() {    
   // 宽字符
   wchar_t wc = L'a';
   // 转换为大写
   wint_t upper_wc = towupper(wc);
   
   wprintf(L"The uppercase equivalent of %lc is %lc", wc, upper_wc);
   return 0;
}

输出

以下是输出 -

The uppercase equivalent of a is A

示例 2

我们创建一个 C 程序来检查字符串是否相等。使用 towupper() 将其转换为大写后,如果两个字符串相等,则表示不区分大小写,否则区分大小写。

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

int main() {
   wchar_t str1[] = L"hello world";
   wchar_t str2[] = L"HELLO WORLD";
   
   // 标志值
   int equal = 1;
   
   // 比较两个字符串
   for (size_t i = 0; i < wcslen(str1); i++) {
      if (towupper(str1[i]) != towupper(str2[i])) {          
         // 字符串不相等
         equal = 0;
         break;
      }
   }
   
   if (equal) {
      wprintf(L"The strings are equal (case insensitive).");
   } else {
      wprintf(L"The strings are not equal.");
   }
   
   return 0;
}

输出

以下是输出 -

The strings are equal (case insensitive).

示例 3

以下示例将宽字符规范化为大写字符。

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

int main() {
   // 宽字符串
   wchar_t text[] = L"Normalize Tutorialspoint!";
   size_t length = wcslen(text);

   wprintf(L"Original text: %ls", text);

   // 将文本标准化为大写
   for (size_t i = 0; i < length; i++) {
      text[i] = towupper(text[i]);
   }
   wprintf(L"Normalized text: %ls", text);
   
   return 0;
}

输出

以下是输出 -

Original text: Normalize Tutorialspoint!
Normalized text: NORMALIZE TUTORIALSPOINT!

❮ C 标准库 - <wctype.h>