How to match text in string in Arduino

2019-04-06 15:42发布

问题:

I have some issues with Arduino about how to match text.

I have:

String tmp = +CLIP: "+37011111111",145,"",,"",0

And I am trying to match:

if (tmp.startsWith("+CLIP:")) {
    mySerial.println("ATH0");
}

But this is not working, and I have no idea why.

I tried substring, but the result is the same. I don't know how to use it or nothing happens.

Where is the error?

回答1:

bool Contains(String s, String search) {
    int max = s.length() - search.length();

    for (int i = 0; i <= max; i++) {
        if (s.substring(i) == search) return true; // or i
    }

    return false; //or -1
} 

Otherwise you could simply do:

if (readString.indexOf("+CLIP:") >=0)

I'd also recommend visiting:

https://www.arduino.cc/en/Reference/String



回答2:

I modified the code from gotnull. Thanks to him to put me on the track.

I just limited the search string, otherwise the substring function was not returning always the correct answer (when substrign was not ending the string). Because substring search always to the end of the string.

int StringContains(String s, String search) {
    int max = s.length() - search.length();
    int lgsearch = search.length();

    for (int i = 0; i <= max; i++) {
        if (s.substring(i, i + lgsearch) == search) return i;
    }

 return -1;
}


回答3:

//+CLIP: "43660417XXXX",145,"",0,"",0
if (strstr(command.c_str(), "+CLIP:")) { //Someone is calling
    GSM.print(F("ATA\n\r"));
    Number = command.substring(command.indexOf('"') + 1);
    Number = Number.substring(0, Number.indexOf('"'));
    //Serial.println(Number);
} //End of if +CLIP:

This is how I'm doing it. Hope it helps.



回答4:

if (tmp.startsWith(String("+CLIP:"))) {
    mySerial.println("ATH0");
}

You can't put the string with quotes only you need to cast the variable :)



标签: arduino