检查字符串是否包含C ++中的所有唯一字符

时间:2017-02-15 03:04:15

标签: c++ string duplicates

我试图找到如果一个字符串包含所有唯一字符,而下面是我的代码,但我收到错误"无效类型' char [int]'对于数组下标"在函数Unique char的if语句中,任何人都可以告诉我如何纠正这个

#include <iostream>
#include<cstring>

using namespace std;
bool unique_char(char);

int main()
{
    char s;
    bool check;
    cout << "Enter any string" << endl;
    cin>>s;
    check = unique_char(s);
    if(check)
        cout<<"there are no duplicates";
    else
        cout<<"the string has duplicates";

    return 0;
}

// The if statement in this section has the error
bool unique_char(char s)
{
    bool check[256] = {false};
    int i=0;
    while (s != '\0')
    {
        if (check **[(int) s[i]]**)
            return false;
        else
        {
         check[(int) s[i]] = true;
         i++;
        }

    }
}

1 个答案:

答案 0 :(得分:0)

您需要传递char数组而不是单个char。

int main()
{
    char s[1000]; // max input size or switch to std::string
    bool check;
    cout << "Enter any string" << endl;
    cin>>s;
    check = unique_char(s);
    if(check)
        cout<<"there are no duplicates";
    else
        cout<<"the string has duplicates";

    return 0;
}

bool unique_char(char* s)
{
    bool check[256] = {false};
    int i=0;
    while (s[i] != '\0')
    {
        if (check[(int) s[i]])
            return false;
        else
        {
         check[(int) s[i]] = true;
         i++;
        }
    }
    return true;
}