C 库 - tolower() 函数



C 的ctypetolower() 函数将给定的字母转换为小写。此函数在需要不区分大小写处理字符的场景中很有用。

语法

以下是 tolower() 函数的 C 库语法:

int tolower(int c);

参数

此函数接受单个参数:

  • c − 该函数接受一个 int 类型的单个参数。此参数是一个无符号 char 值,可以隐式转换为 int,也可以是 EOF。该值表示要转换为小写的字符。

返回值

如果该字符是大写字母,则此函数返回该字符的小写等价物。如果 c 不是大写字母,则函数返回不变的 c。如果 c 是 EOF,则返回 EOF。

示例 1

使用 tolower() 函数将字符 'A' 转换为 'a'。

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

int main() {
   char ch = 'A';
   char lower = tolower(ch);
   printf("Original: %c, Lowercase: %c\n", ch, lower);
   return 0;
}

输出

以上代码产生以下结果:

Original: A, Lowercase: a

示例 2:将字符串转换为小写

此示例演示如何通过迭代每个字符并使用 tolower 将整个字符串转换为小写。

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

void convertToLower(char *str) {
   while (*str) {
      *str = tolower(*str);
      str++;
   }
}

int main() {
   char str[] = "Hello, World!";
   convertToLower(str);
   printf("Lowercase String: %s\n", str);
   return 0;
}

输出

执行以上代码后,我们得到以下结果:

Lowercase String: hello, world!
广告
© . All rights reserved.