You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++技术问询:判断字符串所有字符是否存在于指定数组中

思路与实现建议(C++新手友好)

嘿,刚接触C++碰到这个问题很正常,我来给你拆解一下思路,再给两种适合新手的实现方法~

核心思路

要判断字符串的每个字符都在给定的数组里,本质就是逐个检查字符串的字符是否存在于目标数组中。这里有两个关键点:

  • 查找效率:如果数组不大,直接遍历数组找字符也可以;但如果数组元素多,用哈希集合(比如std::unordered_set)能把单次查找的时间从O(n)降到O(1),更高效。
  • 提前终止:只要发现任何一个字符不在数组里,就可以直接返回false,不用继续检查剩下的字符,节省时间。

方法一:用STL哈希集合(推荐,代码简洁高效)

如果已经开始接触STL容器,这种方法更优雅,适合后续扩展:

#include <iostream>
#include <string>
#include <unordered_set>
#include <vector>

// 定义判断函数:参数是目标字符串和字符集合
bool areAllCharsInLetters(const std::string& str, const std::vector<char>& letters) {
    // 把字符数组转成哈希集合,方便快速查找
    std::unordered_set<char> letterSet(letters.begin(), letters.end());
    
    // 遍历字符串的每个字符
    for (char c : str) {
        // 如果当前字符不在集合里,直接返回false
        if (letterSet.find(c) == letterSet.end()) {
            return false;
        }
    }
    // 所有字符都能找到,返回true
    return true;
}

int main() {
    std::string word = "hello";
    std::string word2 = "hey";
    // 把你原来的字符数组转成vector(也可以直接用数组,不过vector更方便STL操作)
    std::vector<char> letters = {'h', 'e', 'l', 'o'};
    
    // 设置cout输出true/false而不是1/0,更直观
    std::cout << std::boolalpha;
    std::cout << "word的检查结果:" << areAllCharsInLetters(word, letters) << std::endl;
    std::cout << "word2的检查结果:" << areAllCharsInLetters(word2, letters) << std::endl;
    
    return 0;
}

方法二:纯数组遍历(适合理解基础逻辑)

如果还没学STL容器,用最基础的数组嵌套循环也能实现,逻辑更直观:

#include <iostream>
#include <string>

// 参数:目标字符串、字符数组、数组的长度
bool areAllCharsInLetters(const std::string& str, const char letters[], int letterCount) {
    // 遍历字符串的每个字符
    for (char c : str) {
        bool isFound = false;
        // 遍历字符数组,找当前字符
        for (int i = 0; i < letterCount; ++i) {
            if (letters[i] == c) {
                isFound = true;
                break; // 找到就跳出循环,不用继续找
            }
        }
        // 如果当前字符没找到,直接返回false
        if (!isFound) {
            return false;
        }
    }
    // 所有字符都找到,返回true
    return true;
}

int main() {
    std::string word = "hello";
    std::string word2 = "hey";
    char letters[] = {'h', 'e', 'l', 'o'};
    int letterCount = sizeof(letters) / sizeof(letters[0]); // 计算数组长度
    
    std::cout << std::boolalpha;
    std::cout << "word的检查结果:" << areAllCharsInLetters(word, letters, letterCount) << std::endl;
    std::cout << "word2的检查结果:" << areAllCharsInLetters(word2, letters, letterCount) << std::endl;
    
    return 0;
}

测试结果

两种方法运行后都会输出:

word的检查结果:true
word2的检查结果:false

完全符合你的需求~

内容的提问来源于stack exchange,提问作者Prxey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 08:07:35