这个 C 语言程序的逻辑是:从用户读取句子,通过遍历找出句子的长度。将句子长度存入变量 count。之后显示用户输入的句子。然后取字符串的每个字符,使用函数 isupper() 和 islower() 检查它是大写还是小写。
如果字符是大写,它将通过调用函数 tolower() 转换为小写。如果字符是小写,它将通过使用 toupper() 转换为大写。转换后,它将使用函数 putchar(ch) 显示字符。它将重复转换和显示字符,直到到达句子的末尾。
islower() 和 isupper() 函数有什么用?为了检查一个字符是大写还是小写,我们可以使用 C 语言的内置函数 islower() 和 isupper()。
islower() 函数将返回 true。isupper() 函数将返回 true。toupper() 和 tolower() 函数有什么用?toupper()tolower()注意:要使用所有这些函数,我们必须包含头文件 ctype.h。
第一步: 包含头文件,以便在C程序中使用内置函数。
步骤 2:包含头文件 ctype.h 以执行字符测试,例如 isupper(), islower()。
步骤 3:声明字符数组 Sentence[100] 。
步骤 4:从用户那里接收句子到数组 sentence。
步骤 5:通过使用 for 循环遍历句子来找出句子的长度。
步骤 6:在句子的末尾添加一个空字符。
步骤 7:显示给定的句子。
步骤 8:通过使用 for 循环检查字符串的每个字符是“大写”还是“小写”。如果字符是大写,则使用 tolower() 函数将其转换为小写;如果字符是小写,则使用 toupper() 函数将其转换为大写。
步骤 9:转换后,它使用函数 putchar(ch) 显示字符串的每个字符。
要将小写字符转换为大写字符,我们需要使用以下 C 语言主题,我们建议学习以下主题以更好地理解
#include <stdio.h>
#include <ctype.h>
void main()
{
char sentence[100];
int count, ch, i;
printf("Enter a sentence\n");
for (i = 0;
(sentence[i] = getchar()) != '\n'; i++) /* enters the user sentence to change the case*/ {
;
}
sentence[i] = '\0'; /* add the null character at the end of sentence */
count = i; /*shows the number of chars accepted in a sentence*/
printf("The given sentence is : %s", sentence);
printf("\nCase changed sentence is: ");
for (i = 0; i < count; i++) {
ch = islower(sentence[i]) ? toupper(sentence[i]) : tolower(sentence[i]); /* check each letter of sentence using islower function if it is lowercase use toupper function to change it to uppercase else use tolower function to change uppercase to lowercase */
putchar(ch);
}
} /*End of main()*/
Enter a sentence World is Beautiful The given sentence is: World is Beautiful Case changed sentence is: wORLD IS bEAUTIFUL