Substring() not behaving as expected

My code has the following logic:

if ((curFileName.substring(0,8).equals('post2.txt')) || (curFileName.substring(0,8).equals('POST2.TXT')))
{
...
}

I also tried variations of this such as:

(curFileName.substring(0,8) == 'post2.txt')

And:

(curFileName.substring(0) == 'post2.txt')

However, "curFileName" should have the value of 'post.txt' and not 'post2.txt' so the above should evaluate to FALSE . . . YET it seems to evaluate to true because the code nested in that logic is executed.

If i put some debugging code in there to see what happens in the serial monitor such as:

				if ((curFileName.substring(0,8).equals('post2.txt')) || (curFileName.substring(0,8).equals('POST2.TXT')))
				{

Serial.print(curFileName.substring(0,8));
Serial.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");

... etc . . .
}

The serial monitor prints:

post.txtaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

showing that curFileName.substring(0,8) == post.txt and should evaulate to false because the IF is comparing the curFileName.substring(0,8) to the string 'post2.txt' OR 'POST2.TXT' which 'post.txt' clearly is not . . .

I don't know what I am missing here . . .

Thank you in advance

You are using single quote characters, instead of double "". Single quotes can only be used to denote a single character.

Thank you aarg. Made that change, and using:

if ((curFileName.substring(0) == "post2.txt") . . .

worked. I had a feeling it was something simple like that specific to C as a language. In PHP (which is what I am used to) the difference between single and double quotes has different implications. Single quotes can be more efficient in PHP because the string isn't parsed for variables, while you can embed a var in a quoted string in PHP . . . but I digress.

1 Like

Another thing to be aware of from: substring() - Arduino Reference

Look at the description of what is included in the substring:

Get a substring of a String. The starting index is inclusive (the corresponding character is included in the substring), but the optional ending index is exclusive (the corresponding character is not included in the substring). If the ending index is omitted, the substring continues to the end of the String.

All clear now ?

Yes i get it. That makes sense. Cool screen name btw.

You already get top marks for understanding that the index begins at zero, a fact which is omitted from the "documentation". Yes, I explained a bit about the origins of my screen name here: Are there any young Arduino enthusiasts? - #13 by 6v6gt

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.