Mrowkacala - 3 months ago 17

C++ Question

I want to have a function that counts number of unique characters. If for example i have

`aabbcc`

`3`

`aab`

`2`

My attempt was to construct a function that is checking whether number appeared previously and then us it as

`if`

My code is:

`bool firstocc(char* t, int i){`

for(int j = 0;j < i;j++){

if(t[j] == t[i]) return false;

return true;

}

}

int h(char* t){

int c=0;

for(int i=0; t[i+1]!=0;i++){

if(firstocc(t,i)){

c++;

}

return c;

}

}

int main()

{

cout<< h("aabbc");

}

Function always returns zero. What is wrong with it?

Answer

The problem was with the braces in both functions `firstocc`

and `h`

(maybe because a bad indentation, always try take care with indent your code properly, not for compiler but for yourself), and with the loop of function `h`

where the condition was `t[i+1] != 0`

and should be `t[i] != 0`

(to include the last char).

The code should be:

```
bool firstocc(char* t, int i){
for(int j=0;j<i;j++)
if(t[j]==t[i])
return false;
return true;
}
int h(char* t){
int c=0;
for(int i=0; t[i]!=0;i++)
if(firstocc(t,i)){
c++;
}
return c;
}
```

I tested it with `"aabbcddddeaa"`

and it returns 5.