题解 | #计算某字符出现次数#

计算某字符出现次数

https://www.nowcoder.com/practice/a35ce98431874e3a820dbe4b2d0508b1

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

int main() {
    int str_len = 0;
    char str[1024] = {0};
    int ch;
   
    if ( fgets(str, 1024, stdin) != NULL) {
        str[strcspn(str, "\n")] = 0;
    }

    ch = fgetc(stdin);

    char ch2 = 0;
    if (ch >= 'a' && ch <='z') {
        ch2 = toupper(ch);
    }
    else if (ch >='A' && ch <= 'Z') {
        ch2 = tolower(ch);
    }


    int i = 0;
    int num = 0;
    while(str[i] != '\0') {
        if (str[i] == ch || str[i] == ch2) {
            num++;
        }
        i++;
    }
    printf("%d", num);
    return 0;
}

收获:

①读取一行终端输入代码

注意:如果是最多输入1000个字符,要注意 在输入字符串完毕后会有'\n', '\r' 的两个符号。

所以 fgets 函数调用中获取的最大长度应该是 1002,而不能是1000

 char str[1024] = {0};
    int ch;
   
    if ( fgets(str, 1024, stdin) != NULL) {
        str[strcspn(str, "\n")] = 0;
    }

②字符的大小写转换,可以通过库函数实现

#include <ctype.h>

ch = fgetc(stdin);
char ch2 = 0;
if (ch >= 'a' && ch <='z') {
  ch2 = toupper(ch);
}
else if (ch >='A' && ch <= 'Z') {
  ch2 = tolower(ch);
}

③字符的大小写转换,也可以通过计算来实现,但是要知道在ASCII表中,大写字母在前

#include <stdio.h>


int main()
{
    char ch = 'a';

    char ch2 = 'a' - ('a' - 'A');

    printf("ch2:%c\n", ch2);
    return 0;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务