Hey guys, I have the following two pieces of code and I am trying to combine them so it will say if hello is found and it is at the start or the prevous character is whitespace then add one to the count but when i try to combine these two pieces of code to do that my syntax is all wrong.

Any help would be great. Thanks.

char * ch = array;
while((ch = strstr( ch, "hello")) != 0)
{
 Count++;
ch++;
}
if(ch == array || isspace(*(ch-1)))
{
	count++					
	ch++							
	}

Dani AI

Generated

Short summary and fixes that build on the points from , and .

The pointer+strstr approach is fine, but two subtle bugs often slip in: (1) using continue without advancing the search pointer causes an infinite loop (strstr will find the same match again), and (2) passing a plain char to isspace can be undefined if char is signed. Static analyzers may also warn about array[-1] even when guarded. A safer, clearer C++ approach is to use std::string::find and explicit boundary checks.

Example (safe, handles word boundaries and overlapping matches):

std::string s = array;                // or read into a std::string
const std::string needle = "hello";
size_t pos = 0;
while ((pos = s.find(needle, pos)) != std::string::npos) {
    bool left_ok = (pos == 0) ||
        std::isspace(static_cast<unsigned char>(s[pos - 1]));
    bool right_ok = (pos + needle.size() >= s.size()) ||
        std::isspace(static_cast<unsigned char>(s[pos + needle.size()]));
    if (left_ok && right_ok) ++count;
    ++pos; // use pos += needle.size() to skip non-overlapping matches
}

Notes and troubleshooting tips:

  • If staying with C-style pointers, always advance the pointer before continue (or do the check so the pointer is incremented in every path). Check ch != array (or ch > array) before reading ch[-1].
  • Cast to unsigned char when calling isspace/isalnum to avoid UB.
  • If punctuation should be treated as a boundary, replace the right/left checks with !std::isalnum(...) or use a regex with \b for true word-boundary semantics (at the cost of performance).

Recommended Answers

All 2 Replies

char * ch = array;
while((ch = strstr( ch, "hello")) != 0) {
    if(ch != array && !isspace(ch[-1])) continue;
    Count++;
    ch++;
}

That should work.

And yes, array[-1] is valid. :)

isspace() is in <ctype.h> (or, in C++, <cctype>).

And yes, array[-1] is valid. :)

It may be valid, but I am starting to see some modern compilers complain about it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.