已知一段存在边界错误且可优化的C++字符统计函数,以下哪个选项是对其正确的修正与优化后的实现?

cg810846 单选题 共 个子题

原始错误代码如下:

int countTargetChar(const string& str, char target) {
    int count = 0;
    for(int i = 0; i <= str.length(); ++i) {
        if(str[i] == target) {
            ++count;
        }
    }
    return count;
}
A
int countTargetChar(const string& str, char target) {
    int count = 0;
    for(int i = 0; i < str.length(); ++i) {
        if(str[i] == target) {
            ++count;
        }
    }
    return count;
}
B
int countTargetChar(const string& str, char target) {
    int count = 0;
    size_t len = str.length();
    for(int i = 0; i < len; ++i) {
        if(str[i] == target) {
            ++count;
        }
    }
    return count;
}
C
int countTargetChar(const string& str, char target) {
    int count = 0;
    for(int i = 1; i <= str.length(); ++i) {
        if(str[i] == target) {
            ++count;
        }
    }
    return count;
}
D
int countTargetChar(const string& str, char target) {
    int count = 0;
    for(int i = 0; i < str.length(); ++i) {
        if(str[i] == target) {
            ++count;
        }
    }
    if(count > str.length()) count = str.length();
    return count;
}
正在加载题目数据…
已答 /
子题
该题型需在试卷/作业中作答,单题练习暂不支持
答案解析
讨论
发布
登录后参与讨论 立即登录
发布讨论需先绑定并验证手机号 去绑定手机号
加载中…
我
我
回复 @
回复 @
发送
还没有人讨论,来发表第一条吧