【问题标题】:Lowercase to Uppercase and Uppercase to Lowercase in CC中的小写到大写和大写到小写
【发布时间】:2012-11-13 10:34:29
【问题描述】:

有人会帮我处理这段代码吗?编写主题中需要做的函数。可以吗?我还需要计算所做更改的数量。这个怎么实现?

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);

【问题讨论】:

标签: c uppercase lowercase


【解决方案1】:

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

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

如果您想将字符更改为小写,则将其更改为大写,如果是大写,则将其改写为小写:

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])

【讨论】:

    【解决方案2】:

    要计算更改的数量,只需创建一个变量 (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);
     }
    

    【讨论】:

    • 我明白了,已经完成了。但是查看整个代码......它是否完成了编写? :)
    • @user9000 它运行得太快了... ;)
    猜你喜欢
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    相关资源
    最近更新 更多