簡體   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