我正在编写一个C程序,从标准输入中逐一读取字符,将所有大写字符转换为小写,将所有小写字符转换为大写,并将结果写入标准输出。 我还想计算我读了多少个字符,以及其中每个方向上转换了多少个字符,并在最后输出总数。
例如 - Radha Krishna! 会变成
拉达克里希纳!
总共读取15个字符,10个转大写,2个转小写
这是我的代码:-
#include <stdio.h>
#include <ctype.h>
int main()
{
char sentence[100];
int count, ch, i;
printf("Enter a sentence \n");
for (i = 0; (sentence[i] = getchar()) != '\n'; i++)
{
;
}
sentence[i] = '\0';
/* shows the number of chars accepted in a sentence */
count = i;
for (i = 0; i < count; i++)
{
ch = islower(sentence[i])? toupper(sentence[i]) :
tolower(sentence[i]);
putchar(ch);
}
}
它正在从大写转换为小写,反之亦然,但我不知道如何计数。
最佳答案
将三元组更改为 if/else 子句,并为每个条件提供计数器。
int changedToLower = 0;
int changedToUpper = 0;
for (i = 0; i < count; i++) {
char oldC = sentence[i];
if(islower(sentence[i])) {
ch = toupper(sentence[i])
changeToUpper += (ch != oldC)? 1 : 0;
} else {
ch = tolower(sentence[i]);
changeToLower += (ch != oldC)? 1 : 0;
}
}
关于将所有小写字符转换为大写字符,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40072980/