C String Uppercase: strupr()

In the C programming language, strings are represented as arrays of characters. There are several functions available to manipulate strings, and one such function is strupr(). The strupr() function is used to convert all lowercase characters in a string to uppercase.

The strupr() function takes a string as an argument and modifies it in place by converting all lowercase characters to uppercase. It does not return a new string; instead, it modifies the original string.

Here is the syntax of the strupr() function:

char* strupr(char* str);

The strupr() function is part of the string.h library, so you need to include this header file in your program to use the function. Here’s an example of how to use the strupr() function:

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

int main() {
   char str[] = "Hello, World!";
   
   printf("Original string: %sn", str);
   
   strupr(str);
   
   printf("Uppercase string: %sn", str);
   
   return 0;
}

In this example, we have a string "Hello, World!". We first print the original string using the printf() function. Then, we use the strupr() function to convert all lowercase characters in the string to uppercase. Finally, we print the modified string, which now contains "HELLO, WORLD!".

It’s important to note that the strupr() function only works with ASCII characters. If your string contains non-ASCII characters, the behavior of the function is undefined.

Additionally, the strupr() function is not available in all C compilers, as it is not part of the C standard library. If you’re using a compiler that doesn’t support strupr(), you can implement your own function to convert lowercase characters to uppercase.

Here’s an example of a custom strupr() function:

void strupr(char* str) {
   while (*str) {
      if (*str >= 'a' && *str <= 'z') {
         *str -= 32;
      }
      str++;
   }
}

This custom strupr() function iterates through each character in the string and checks if it is a lowercase character. If it is, it subtracts 32 from the ASCII value of the character to convert it to uppercase.

Using the strupr() function or implementing your own version can be useful when you need to convert a string to uppercase in your C programs. It provides a convenient way to ensure consistent capitalization or when comparing strings without considering case sensitivity.

Remember to always check the documentation of your specific C compiler to ensure that the strupr() function is available and supported.

Scroll to Top