Mroweczka Mroweczka - 13 days ago 5
C++ Question

A function for finding n consecutive characters returning true/false

I want to have a function that is going return true if and only if when

char*
s contains sequence of n consecutive identical signs. For example if we have
"aaac"
and
n=3
i want the function to return true.

My idea for the code is:

bool g(char* s, int n){
if(s[0]==0) return true;
for (int i=0; s[i+1]!=0;i++){
for (int j=i; s[i+1]!=0;j++){
while(int a != n){
if(s[i]==s[i+j]){
a++;
}
}
}
}
}
int main() {
cout<< g("aaac",3);
}


I know that the code is incomplete however the problem is that i do not know where do i need to
return true
and where to put
return false
.

PLEASE rather then down voting this question please explain what is wrong with it?

Answer

Your function is needlessly complex. You can do it with a single loop, like this:

  • Make a counter, and set it to zero
  • Examine each pair of consecutive characters, i.e. *s and *(s+1)
  • If they are not the same, set counter to zero
  • Otherwise, increment the counter; if it reaches n, return true.
  • If you reach the end of the loop, when s points to null terminator, return false.

Checking the difference can be done like this:

if (*(s+1) == *s) {
    count++;
    if (count == n) {
        return true;
    }
} else {
    count = 0;
}