Mindaugas
Mindaugas

Reputation: 326

How to match text in string in Arduino

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?

Upvotes: 7

Views: 29027

Answers (4)

ZiTAL
ZiTAL

Reputation: 3581

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

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

Upvotes: 2

gotnull
gotnull

Reputation: 27214

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

Upvotes: 7

Georgian
Georgian

Reputation: 21

//+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.

Upvotes: 2

Ydakilux
Ydakilux

Reputation: 627

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;
}

Upvotes: 2

Related Questions