MST

星途 面试题库

面试题:C++中字符常量与字符串常量比较操作的基础实现

请编写一段C++代码,实现判断一个字符常量是否与字符串常量中的某一个字符相等,并输出结果。要求代码清晰,使用合适的控制结构和字符串操作方法。
27.3万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>
#include <cstring>

int main() {
    const char ch = 'a';
    const char str[] = "hello";
    bool found = false;

    for (size_t i = 0; i < strlen(str); ++i) {
        if (str[i] == ch) {
            found = true;
            break;
        }
    }

    if (found) {
        std::cout << "字符 '" << ch << "' 在字符串 '" << str << "' 中" << std::endl;
    } else {
        std::cout << "字符 '" << ch << "' 不在字符串 '" << str << "' 中" << std::endl;
    }

    return 0;
}