Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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();
   content.concat(character23); 
  }    
if (content != "") {
  l1 = content;
  Serial.println(l1 + "\n");
}

if(l1.substring(0) == "print"){
  printlnMethod(); 
}
file.close();

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?

share|improve this question
up vote 0 down vote accepted

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.

share|improve this answer
    
I already tried that and it didn't work – user2279603 Feb 15 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 at 22:17
    
I'm not sure how to return a substring – user2279603 Feb 15 at 22:22
    
Serial.println(l1.substring(0,5)); – Majenko Feb 15 at 22:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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