C语言tolower函数用于把大写字母转换为小写字母。

在本文中,我们先来介绍tolower函数的使用方法,然后编写一个自定义的_tolower函数,实现与tolower函数相同的功能。

1、包含头文件

#include <ctype.h>

2、函数声明

int tolower(int c);

3、功能说明

把大写字母转换为小写字母,如果参数c不是大写字母就不转换,您可能会问:tolower函数的参数和返回值是整数,不是字符,在C语言中,字符就是整数,请补充学习一下基础知识。

参数c为待转换的字符。

返回值为转换后的结果。

4、示例

#include <stdio.h>

int main()
{
  printf("tolower('-')=%c\n",tolower('-'));
  printf("tolower('0')=%c\n",tolower('0'));
  printf("tolower('a')=%c\n",tolower('a'));
  printf("tolower('A')=%c\n",tolower('A'));
}

运行效果

介绍C语言中tolower函数的实例

5、自定义的tolower函数的实现方法

在以下示例中,把自定义的tolower函数命名为_tolower。

程序的逻辑是:判断参数c是否为大写字母,如果是则加上32(小写字母和大写字母的ASCII码值相差32),如果不是直接返回原字符。

#include <stdio.h>

// 自定义的tolower函数。
int _tolower(int c)
{
  if (c>='A' && c<='Z') return c+32;
  else return c;
}

int main()
{
  printf("_tolower('-')=%c\n",_tolower('-'));
  printf("_tolower('0')=%c\n",_tolower('0'));
  printf("_tolower('a')=%c\n",_tolower('a'));
  printf("_tolower('A')=%c\n",_tolower('A'));
}

运行效果

介绍C语言中tolower函数的实例

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。