Hello I have an Arduino programme where a string is loaded from an SD card. That all works fine. I want to see if the string that has been loaded contains a certain phrase. I am using substring but it doesn't seem to be working. What am I doing wrong? Here's my code:

file = SD.open("/classes/basic.txt", FILE_READ);
 Serial.print("Reading, Checking and Compiling \n");  
  while(file.available()) {
   character23 = file.read();
if (content != "") {
  l1 = content;
  Serial.println(l1 + "\n");

if(l1.substring(0) == "print"){

it all works until it gets to l1.substring and that doesn't work because the method inside doesn't run. The string that gets loaded into the Arduino from the SD card is : println("hello world");

What am I doing wrong?


Substring takes either one or two arguments.

In the single-argument version that you are using the argument specifies the start of the substring. The substring then contines to the end of the string. So, since you are asking it to start at index 0 the returned value is the entire string - from 0 to the end.

Instead you probably want to use the two-argument version. In that version you provide two numbers - the index in the string to start from, and the index in the string after the last character you want. So if the string starts with "print" you then want to use l1.substring(0, 5) to get the characters 0 to 4 inclusive.

| improve this answer | |
  • I already tried that and it didn't work – user2279603 Feb 15 '16 at 22:16
  • 2
    Try printing what substring returns so you can see what it's really doing. Your string might not be exactly what you think it is. – Majenko Feb 15 '16 at 22:17
  • I'm not sure how to return a substring – user2279603 Feb 15 '16 at 22:22
  • Serial.println(l1.substring(0,5)); – Majenko Feb 15 '16 at 22:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.