Find if a string begins with a specific set of characters in Arduino


The startsWith() function in Arduino helps you determine if a string starts with a specific set of characters. It returns true if the string starts with the substring you specified, else it returns false. An example implementation is given below −

Example

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   String String1 = "AB_Test";
   String String2 = "CD_Test";
   String substr1 = "AB";
   String substr2 = "AB*";
   if(String1.startsWith(substr1)){
         Serial.print("String1 starts with substr1");
      }
   if(String2.startsWith(substr1)){
         Serial.print("String2 starts with substr1");
      }
   if(String1.startsWith(substr2)){
         Serial.print("String1 starts with substr2");
      }
   if(String2.startsWith(substr2)){
         Serial.print("String2 starts with substr2");
      }
}
void loop() {
   // put your main code here, to run repeatedly
}

As you can expect, this program will print "String1 starts with substr1" only. The corresponding Serial Monitor output is shown below (the garbage characters in the beginning are programming/ start-up noise) −

Output

Updated on: 24-Mar-2021

484 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements