要检查一个字符串是否具有所有唯一字符在C + +

问题描述:

我试图找到如果一个字符串具有所有的唯一字符和以下是我的代码,但我得到错误“数组下标”无效类型'char [int]'in函数Unique char的if语句,谁能告诉我如何解决这个问题要检查一个字符串是否具有所有唯一字符在C + +

#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++; 
     } 

    } 
} 
+0

你觉得你可以装入一个'char'字符多少个字符? –

+0

来自''标题的'std :: string'类型变量可以保存任意长度的文本字符串。 –

您需要传递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; 
}