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.