C中小写到大写,大写到小写

时间:2012-11-25 23:10:17

标签: c uppercase lowercase

有没有人会帮我这个代码?函数需要像在主题中那样写。好吗?我需要的是计算所做更改的数量。如何实现这一个?

int change(char *path){

FILE *f = fopen(path, "r");
if(f==NULL){
    printf("Error...");
    return -1;
}
int text, length;

    fscanf(f, "%s", &text);
    length = strlen(text);

 for(i = 0; i < length; ++i){
    if(islower(text[i]))
          {
          text[i] = toupper(text[i]);
          }
    if(isupper(text[i]))
    {
        text[i] = toslower(text[i]);
    }
fprintf(f,"%s",text);
fclose(f);

2 个答案:

答案 0 :(得分:1)

要计算更改次数,只需创建一个变量(int count = 0),并在每次更改时将其递增(count++)。

int change(char *path){


    FILE *f = fopen(path, "r");

    if(f==NULL){
        printf("Error...");
        return -1;
    }

    int text, length;
    int count = 0;

    fscanf(f, "%s", &text);
    length = strlen(text);

    for(i = 0; i < length; ++i){
        if(islower(text[i]))
        {
            text[i] = toupper(text[i]);
            count++;
        }
        if(isupper(text[i]))
        {
            text[i] = tolower(text[i]);
            count++;

        }
    }

    fprintf(f,"%s",text);
    fclose(f);
 }

答案 1 :(得分:1)

现在您的代码将首先尝试将文本从小写更改为大写,然后如果成功则将其更改回小写。我认为这不是你想要的,因为你现在有两种情况,要么是从低到高再到低,要么根本不变。

为了跟踪这些变化,我们添加了一个变量“changes”,我们将其初始化为零。

相反,如果您希望将字符更改为大写,如果它是小写,则小写更改为大写,如果大写,则重写如下:

if(islower(text[i])) {
    text[i] = toupper(text[i]);
    changes++;
} else if(isupper(text[i])) { 
    text[i] = tolower(text[i]);
    changes++;
}

还有一个拼写错误,toslower(text [i])但我认为你的意思是tolower(text [i])