inString function.

Was looking for a way to search for a string within a string, didn’t find anything after searching for a while. This is what I came up with. Hope helps… comments/improvements welcome.

int inString(String evalString = String(30), String searchString = String(30)) {
  int startPos;
  int endPos;
  int result;
  result = 0;
  if (evalString.length() == searchString.length()) {
    if (evalString == searchString) {
      result = 0;
      return result;
    }
  } 
  if (evalString.length() < searchString.length()) {
    result = -1;
    return result;
  }

  for (int x = 0; x < evalString.length(); x++){  
    //Serial.print(x);
    //Serial.print(',');
    //Serial.print(x + searchString.length());
    //Serial.print(':');
    //Serial.print(evalString.substring(x , x + searchString.length()));
    //Serial.print('\n');

    if (x + searchString.length() >= evalString.length()){
      result = -2;
      return result;
    }
    if (evalString.substring(x , x + searchString.length()) == searchString) {
      result = x;
      return result;
    }
  }
  result = -2;
  return result;
}

Right.... indexOf() might have solved my problem...

I use the “indexof” in the below test code to test for the string “woohoo”.

//zoomkat 9-9-10 simple delimited ',' string parce
//from serial port input (via serial monitor)
//and print result out serial port
// CR/LF could also be a delimiter
//

String readString; // = String(100);

void setup() {
  Serial.begin(9600);
}

void loop() {

  //expect a string like wer,qwe rty,123 456,hyre kjhg,
  //or like hello world,who are you?,bye!,
  while (Serial.available()) {
    delay(10);  //small delay to allow input buffer to fill
    if (Serial.available() >0) {
      char c = Serial.read();  //gets one byte from serial buffer
      if (c == ',') {
        break;
      }  //breaks out of capture loop to print readstring
      readString += c;
    } //makes the string readString
  }

  if (readString.length() >0) {
    Serial.println(readString); //prints string to serial port out

    if(readString.indexOf("woohoo") >=0) {
      Serial.println("I found woohoo!"); 
    }

    readString=""; //clears variable for new input
  }
}