简体   繁体   English

将char数组元素转换为大写或小写

[英]convert char array elemnts to upper or lower case

For my homework assignment we are asked to get a string from the user and: 对于我的家庭作业,我们要求从用户处获取一个字符串,并:

  1. convert it all to uppercase = completed 全部转换为大写=已完成
  2. convert it all to lowercase = completed 全部转换为小写=完成
  3. convert the each character if it is upper to lower and vice versa. 如果每个字符从上到下转换,反之亦然。 (problem) (问题)

I do not know if my logic is wrong or if it's a simple fix. 我不知道我的逻辑是错误的还是简单的解决方法。 Any suggestions are appreciated. 任何建议表示赞赏。

#include <stdio.h>


int main()
{
int i;
char sentense [30];
printf("Please enter a sentence\n");
fgets(sentense, 30, stdin);

for(i=0; sentense[i] != '\0'; i++)
{
    putchar(toupper(sentense[i]));
}

for(i=0; sentense[i] != '\0'; i++)
{
    putchar(tolower(sentense[i]));
}

for(i=0; sentense[i] != '\0'; i++)
{
    if(sentense[i] >='65' && sentense[i] <='90')
    {
        putchar(tolower(sentense[i]));
    }


    else if(sentense[i] >= '97' && sentense[i] <='122')
    {
        putchar(tolower(sentense[i]));
    }
    else
    {

    }
}



return 0;
}

You need to change 你需要改变

if(sentense[i] >='65' && sentense[i] <='90')

to

if(sentense[i] >= 65 && sentense[i] <= 90)

and rest case(s) as we want to compare the integer value here. 和其余的情况,因为我们想在这里比较整数值。

Enable the compiler warning and your compiler should be warning you about the mistake. 启用编译器警告,您的编译器应警告您有关错误。

Alternatively, you can also make use of isupper() / islower() library functions, too. 另外,您也可以使用isupper() / islower()库函数。

  • you should use isupper and islower to prevent the code to depend on character codes. 您应该使用isupperislower来防止代码依赖于字符代码。
  • you should use toupper instead of tolower to convert letters to uppercase. 您应该使用toupper而不是tolower将字母转换为大写。
  • you may have to print characters other than English alphabets. 您可能必须打印英文字母以外的字符。

Fixed code: 固定代码:

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


int main()
{
    int i;
    char sentense [30];
    printf("Please enter a sentence\n");
    fgets(sentense, 30, stdin);

    for(i=0; sentense[i] != '\0'; i++)
    {
        putchar(toupper(sentense[i]));
    }

    for(i=0; sentense[i] != '\0'; i++)
    {
        putchar(tolower(sentense[i]));
    }

    for(i=0; sentense[i] != '\0'; i++)
    {
        if(isupper(sentense[i]))
        {
            putchar(tolower(sentense[i]));
        }


        else if(islower(sentense[i]))
        {
            putchar(toupper(sentense[i]));
        }
        else
        {
            putchar(sentense[i]);
        }
    }
    return 0;
}

Easy to understand, you should compare directly. 易于理解,您应该直接进行比较。 Let's use: 让我们使用:

if(sentense[i] >='A' && sentense[i] <='Z') 

to check the up-case. 检查大写。 And use: 并使用:

if(sentense[i] >='a' && sentense[i] <='z') 

to check the low-case. 检查小写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM