[英]C Program to check if character is a lower case letter and convert to upper case letter and vice versa
C Program to check if character is a lower case letter and convert to upper case letter and vice versa C 程序检查字符是否为小写字母并转换为大写字母,反之亦然
why this works?为什么这行得通?
(it seems to be working if i use if statement twice but not if i use if-else statement) (如果我使用 if 语句两次,但如果我使用 if-else 语句,它似乎可以工作)
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch , k ;
printf("enter an alphabet : ");
scanf("%c",&ch);
if (ch>=97 && ch<=122)
{
printf(" \n small letter");
k=ch-32;
printf(" \n after conversion %c",k);
}
if (ch>=65 && ch<=90)
{
printf(" \n capital letter");
k=ch+32;
printf(" \n after conversion %c",k);
}
return 0;
}
but this displays a random value.但这会显示一个随机值。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch , k ;
printf("enter an alphabet : ");
scanf("%c",&ch);
if (ch>=97 && ch<=122)
{
printf(" \n small letter");
k=ch-32;
printf(" \n after conversion %c",k);
}
else (ch>=65 && ch<=90);
{
printf(" \n capital letter");
k=ch+32;
printf(" \n after conversion %c",k);
}
return 0;
}
if (ch>=97 && ch<=122)
it will only work with ASCII codes. if (ch>=97 && ch<=122)
它只适用于 ASCII 码。 It is not portable.它不是便携式的。 C has special functions for this task:
C 具有此任务的特殊功能:
#include <ctype.h>
int swapCase(int ch)
{
return isupper((unsigned char)ch) ? tolower((unsigned char)ch) : toupper((unsigned char)ch);
/*
//or
if(isupper((unsigned char)ch))
ch = tolower((unsigned char)ch);
else
ch = toupper((unsigned char)ch);
return ch;
*/
}
and some helper function and the main program to demonstrate how it works:和一些助手 function 和主程序来演示它是如何工作的:
char *strSwapCase(char *str)
{
char *wrk = str;
if(str)
{
while(*str)
{
*str = swapCase(*str);
str++;
}
}
return wrk;
}
int main (void){
char x[] = "asDrgdfDFGHFDSdfgf3546&&&434fdgffyhfghfdfsdgsfdDFDGdfgdf";
printf("before: %s\n", x);
printf("after : %s", strSwapCase(x));
}
https://godbolt.org/z/E4oe99sGd https://godbolt.org/z/E4oe99sGd
Your second code, as written, does not compile.您编写的第二个代码无法编译。 If you meant to use "else if", it should be written:
如果您打算使用“else if”,则应编写为:
else if (ch>=65 && ch<=90)
Correcting this line causes your code to both compile and behave as expected.更正此行会使您的代码编译并按预期运行。 As it stands, I'm not sure how your code is running and giving you a "random value", but you may be using some unusual compiler that's discarding the statement after your
else
?就目前而言,我不确定您的代码是如何运行并为您提供“随机值”的,但是您可能正在使用一些不寻常的编译器,它在
else
之后丢弃了该语句?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.