Find Text error i think

Not sure if I'm reporting this in the correct location.

I am quite sure I have discovered an error in the example code found on the following link.

Find Text Example code on this site:
http://playground.arduino.cc/Main/FindText

char Haystack[] = "this is a test";
char Needle[] = "test";
Serial.println(find_text(Needle, Haystack));

returns -1

Clearly "test" is located in the string

for (int i = 0; (i < haystack.length() - needle.length()); i++) {
should read:
for (int i = 0; (i <= haystack.length() - needle.length()); i++) {

now it returns 10

Hope this helps someone :slight_smile:

Thank you. I have changed it. That code is for String objects. For normal text the strstr() could be used.

Thank you
I forgot about strstr()

glad I could help :slight_smile:

to use strstr() in the same way as find_text() i had to do the following

 char Haystack[] = "this is a test";
  char Needle[] = "test";
  Serial.println(Haystack);
  Serial.println(Needle);
  char * Pointer;
  Pointer = strstr(Haystack, Needle);
  Serial.println(&Pointer[0] - &Haystack[0]); // subtract the starting pointer of Haystack from the pointer returned by strstr()
  Serial.println(find_text(Needle, Haystack));

Returns 10 for both tests :slight_smile:

again thank you for the strstr()

Hi guys! I know this post is a bit old, but since it helped me a lot when looking for a simple, clean way to find text in strings, I decided to put my 2 cents in.
In case the needle is bigger than the haystack, the for loop will never end, which is not what a for loop is meant for in the first place, so it must be placed in a conditional if() or while() (I like to code with those two mostly). For example, it would look like this:

int find_text(String needle, String haystack)
{
int foundpos = -1;
if (needle.length() <= haystack.length())
{
for (int i = 0; i <= haystack.length() - needle.length(); i++)
{
if (haystack.substring(i,needle.length()+i) == needle)
foundpos = i;
}
}
return foundpos;
}

EDIT: I decided to post this so this "bug" would be considered and put in the description of the Arduino Playground site. Or use my code. Either way, I think it must be considered and mentioned for posterity.

In case the needle is bigger than the haystack, the for loop will never end

If needle.length() is 20 and haystack.length() is 10, the for loop will be

   for (int i = 0; i <= -10; i++)

That reads "starting with i equal to 0, while i is less than or equal -10, do some stuff, increment i by 1, and check the while condition again.

Since 0 is not less than, or equal to -10, the body of the for statement will never be executed.

The if test you added is not needed. The "bug" is in your understanding of a for statement.