C library - towupper() function



The C wctype library towupper() function is used to convert the given wide character to the uppercase, if possible.

This function can be useful for case insensitive comparison, text normalization, or user input processing.

Syntax

Following is the C library syntax of towupper() function −

wint_t towupper( wint_t wc );

Parameters

This function accepts a single parameter −

  • wc − It is a wide character of type 'wint_t' to be converted into uppercase.

Return Value

This function returns uppercase character if the wide character has changed to a uppercase character, otherwise unchanged character (if it is already uppercase or not an alphabetic character)

Example 1

The following is the basic c example that demonstrate the use of towupper() function.

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

int main() {    
   // wide character
   wchar_t wc = L'a';
   // convert to upper
   wint_t upper_wc = towupper(wc);
   
   wprintf(L"The uppercase equivalent of %lc is %lc\n", wc, upper_wc);
   return 0;
}

Output

Following is the output −

The uppercase equivalent of a is A

Example 2

We create a c program to check strings are equal or not. after converting to uppercase using the towupper(). If both strings are equal, it means case insensitive, otherwise sensitive.

#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";
   
   // flag value
   int equal = 1;
   
   // comepare both string after compare
   for (size_t i = 0; i < wcslen(str1); i++) {
      if (towupper(str1[i]) != towupper(str2[i])) {          
         // strings are not equal
         equal = 0;
         break;
      }
   }
   
   if (equal) {
      wprintf(L"The strings are equal (case insensitive).\n");
   } else {
      wprintf(L"The strings are not equal.\n");
   }
   
   return 0;
}

Output

Following is the output −

The strings are equal (case insensitive).

Example 3

The below example, normalized the wide character into a uppercase character.

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

int main() {
   // Wide string 
   wchar_t text[] = L"Normalize Tutorialspoint!";
   size_t length = wcslen(text);

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

   // Normalize the text to uppercase
   for (size_t i = 0; i < length; i++) {
      text[i] = towupper(text[i]);
   }
   wprintf(L"Normalized text: %ls\n", text);
   
   return 0;
}

Output

Following is the output −

Original text: Normalize Tutorialspoint!
Normalized text: NORMALIZE TUTORIALSPOINT!
c_library_wctype_h.htm
Advertisements