繁体   English   中英

C ++如何使用find函数在char数组中查找char?

[英]C++ How to find char in a char array by using find function?

如何使用find函数在char数组中查找char? 如果我只是循环元音,那么我可以得到答案,但我被要求使用 std::find ......谢谢。

bool IsVowel (char c) { 

    char vowel[] = {'a', 'e', 'i', 'o', 'u'};            
    bool rtn = std::find(vowel, vowel + 5, c);

    std::cout << " Trace : " << c  << " " << rtn << endl;

    return rtn; 
 }
bool IsVowel (char c) { 

    char vowel[] = {'a', 'e', 'i', 'o', 'u'};
    char* end = vowel + sizeof(vowel) / sizeof(vowel[0]);            
    char* position = std::find(vowel, end, c);

    return (position != end); 
 }

简化和修正

inline bool IsVowel(char c) {
    return std::string("aeiou").find(c) != std::string::npos;
}

查看演示http://ideone.com/NnimDH

std::find(first, last, value)返回一个迭代器,指向与范围 [first, last) 中的value匹配的第一个元素。 如果没有匹配项,则返回last

特别是, std::find 不返回布尔值。 要获得您正在寻找的布尔值,您需要将 std::find 的返回值(而不是先将其转换为布尔值!)与last (即,如果它们相等,则未找到匹配项)。

使用:

size_t find_first_of ( char c, size_t pos = 0 ) const;

参考:http ://www.cplusplus.com/reference/string/string/find_first_of/

在数组中查找字符的序列 - 为什么将 bool 拖入其中。 如果可以,请给出一个简单明了的答案。

    #include <iostream>
    #include <stdio.h>
    using namespace std;
    //Position
    int posc(char suit[], char fc, int sz)
        {
            int i = 0;
            do
            {
                if (toupper(fc) == suit[i]) return i;
                else
                i = i + 1;
            } 
            while (i < sz);
            cout << "\n Character " << fc << " not available in list";
            return 99;
        }
    int main()
    {
        char suit[] = { 'S', 'D', 'C', 'H' };
        char fc;
        int res;
        int sz = size(suit);
        cout << "\n Enter a character: ";
        cin >> fc;
        res = posc(suit, fc, sz);
        cout << "\n Sequence no: " << res;
        return 0;
    }

添加主要和 cout 装饰只是为了显示一个有效的解决方案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM