I am using the following code to compare packetbuffer to a string,
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];
!strcmp(packetBuffer, "turn on light")
however how could I use to compare it to a string should packetbuffer = testing1234 and the string to be compared to equal "testing", with out the last 4 digits?
The function you are looking for is strstr :
if (strstr(packetBuffer, "testing") != NULL)
{
// packetBuffer contains "testing"
// so do something...
}
Note: if you need to test for the substring just at the start of the string then you can do it like this:
if (strstr(packetBuffer, "testing") == packetBuffer)
{
// packetBuffer starts with "testing"
// so do something...
}
If you can use standard C library, strncmp
is useful.
The length is also checked to make sure there are exactly 4 characters (not just digits) after "testing".
if (strlen(packetBuffer) == 11 && strncmp(packetBuffer, "testing", 7) == 0) {
// they are equal
}
Note that this is not very good code since some magic numbers are used.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.