I have tried eveything to count the reccurrence of just the word hello. I open a file and can count the words in the textbox but can't count just the on word that i want. Please help with this problem. thanks

Here is a way to do it, I made a function GetWord which will return a word depending on the index and the gaps you give it. It will loop through all the words and count number of words that match. Hope it helps.

#include<iostream>
using namespace std;

inline bool TextContains(char *txt, char ch) {
	while (*txt) if (*txt++ == ch)
		return 1;
	return 0;
}
inline char *SubStr(char *text, int beg, int end) {
	register int len = end - beg;
	char *cut = new char[len];
	memcpy_s(cut,(rsize_t)len, &text[beg], (size_t)len);
	cut[len] = '\0';
	return cut;
}
int CountWords(char *text, char *gaps) {
	register bool t = 0, ot = 0;
	register int wc = 0, i = 0;
	while (TextContains(gaps, text[i])) i++;
	for (;text[i];i++) {
		t = TextContains(gaps, text[i]);
		if (t != ot) wc++;
		ot = t;
	}
	return (wc/2)+1;
}
char *GetWord(char *text, char *gaps, int bzIndex) {
	int i=0, sc=0, ec=0, g=0;
	for (;text[i] && TextContains(gaps,text[i]);) i++;
	for (sc = i; text[i]; i++) {
		if (TextContains(gaps, text[i])) {
			while (text[i] && TextContains(gaps, text[i+1])) i++;
			if (++g == bzIndex) sc = i + 1;
		} else if (g == bzIndex) {
			while (text[i] && !TextContains(gaps, text[i])) i++;
			ec = i;
			break;
		}
	}
	return SubStr(text, sc, ec);
}

int main() {
	char text[] = "Hello World! Hello World! Hello World!";
	char word[] = "Hello";
	int count = 0;

	for (int i = 0; i < CountWords(text, " !"); i++) {
		if (strcmp(GetWord(text, " !", i), word)==0)
			count++;
	}

	cout << count;

	cin.ignore();
	return 0;
}
This article has been dead for over six months. Start a new discussion instead.