help with const char * and class member functions!

Hello, I am trying to count the number of times that "Ni" occurs in the string "Ni nI NI nI Ni". However, I can't get my code to work. Any help that I could get as soon as possible would be wonderful. Keep in mind that I need to keep the class MyClass, and the getNiCount function within the public section of that class. Also, I need to have const char *szTestString1 = "Ni nI NI nI Ni"; in my main function.


// classes example
#include <iostream>
using namespace std;

class MyClass {

public:
int getNiCount(const char *phrase)
{
int index = 0;
int num_occurences = 0;

while(index != 14){
if(phrase[index] == 'N' && phrase[index+1] == 'i')
{
num_occurences = num_occurences + 1;
}
else
{
index++;
}
}
return num_occurences;
};

int main () {
MyClass phrase1;
const char *szTestString1 = "Ni nI NI nI Ni";
cout << phrase1.getNiCount(szTestString1) << endl;

return 0;
}

You need to advance index whether or not you have incremented the occurrence count

1
2
3
4
5
6
7
8
while(index != 14)
{
  if(phrase[index] == 'N' && phrase[index+1] == 'i')
  {
    num_occurences = num_occurences + 1;
  }
  index++;
}


also make sure you don't go over the end since you are using phrase[index+1] in the loop

Last edited on
Oh my god, how could I have missed that?! Thank you!
Topic archived. No new replies allowed.