C语言小写字母转大写字母 - toupper() 函数详解

在 C 语言中,将小写字母转换为大写字母可以使用标准库函数 toupper()。该函数接受一个字符作为参数,并返回对应的大写字母字符。

以下是使用 toupper() 函数将小写字母 'a' 转换为大写字母的示例代码:

#include <stdio.h>
#include <ctype.h>

int main() {
    char lowercase = 'a';
    char uppercase = toupper(lowercase);
    printf('Uppercase: %c\n', uppercase);

    return 0;
}

代码解释

  1. #include <ctype.h>: 这一行引入了 ctype.h 头文件,该文件包含了 toupper() 函数的声明。
  2. char lowercase = 'a';: 声明一个名为 lowercase 的字符变量,并将其初始化为小写字母 'a'。
  3. char uppercase = toupper(lowercase);: 调用 toupper() 函数,并将 lowercase 变量的值作为参数传递给它。函数返回值(大写字母 'A')存储在名为 uppercase 的字符变量中。
  4. printf('Uppercase: %c\n', uppercase);: 使用 printf() 函数打印结果,将大写字母 'A' 显示在控制台上。

转换整个字符串

要将整个字符串转换为大写字母,可以使用循环遍历字符串中的每个字符,并对每个字符使用 toupper() 函数进行转换。

以下是一个示例代码:

#include <stdio.h>
#include <ctype.h>

int main() {
    char str[] = 'hello world';
    int i;

    for (i = 0; str[i] != '\0'; i++) {
        str[i] = toupper(str[i]);
    }

    printf('Uppercase string: %s\n', str);

    return 0;
}

在这个例子中,我们循环遍历字符串 str,并将 toupper() 函数应用于每个字符,将结果存储回字符串中。最终,打印转换后的字符串,输出结果为 'HELLO WORLD'。

C语言小写字母转大写字母 - toupper() 函数详解

原文地址: https://www.cveoy.top/t/topic/cjix 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录