C 语言字符串转大写函数代码详解

以下代码实现了一个将字符串转换为大写字母的 C 语言函数 toUpperCase,并提供了一个简单的示例程序。

#include <stdio.h>

void toUpperCase(char *str) {
   int i = 0;
   while(str[i] != '\0') {
      if(str[i] >= 'a' && str[i] <= 'z') {
         str[i] = str[i] - 32;
      }
      i++;
   }
}

int main() {
   char str[100];
   printf("Enter a string:");
   scanf("%s", str);

   toUpperCase(str);

   printf("%s\n", str);

   return 0;
}

代码解析

  1. 函数定义:

    • void toUpperCase(char *str) 定义了一个名为 toUpperCase 的函数,它接受一个指向字符数组的指针作为参数,用于存放待转换的字符串。函数返回值类型为 void,表示函数不返回值。
  2. 循环遍历:

    • while(str[i] != '\0') 循环遍历字符串中的每个字符,直到遇到字符串结束符 '\0' 为止。
  3. 判断字符:

    • if(str[i] >= 'a' && str[i] <= 'z') 判断当前字符是否为小写字母。
  4. 转换字符:

    • str[i] = str[i] - 32; 将小写字母的 ASCII 码值减去 32,得到对应的大写字母的 ASCII 码值,并更新字符串数组中的字符。
  5. 主函数:

    • char str[100]; 定义一个字符数组 str,用来存储用户输入的字符串,长度为 100 个字符。
    • printf("Enter a string:"); 提示用户输入一个字符串。
    • scanf("%s", str); 读取用户输入的字符串,并存储到 str 数组中。
    • toUpperCase(str); 调用 toUpperCase 函数,将 str 数组中的字符串转换为大写字母。
    • printf("%s\n", str); 打印转换后的字符串。

示例运行结果

输入:hello

输出:HELLO

总结

这段代码通过循环遍历字符串中的每个字符,并根据 ASCII 码值进行转换,实现了将字符串转换为大写字母的功能。该函数可以作为 C 语言编程中常用的字符处理工具。


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

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