I have a char message and when i convert it to string and using if statement , return false. and when i use compareTo function returns 175, but it should be 0.
char message[dataSize] ;
// message is ASDFGT
String id = "ASDFGT"
if (String(message) == id){
Serial.println("Strings are equal")
}
i think the problem is converting char to string but how can i handle that?
Serial.println(String(message).compareTo(id));
//returns 175 but it should be 0
and ihave the same problem in python
CodePudding user response:
char array and string object is different objects, equals function compare thats pointers, you need to convert char array into string object and then compare it
char message[dataSize];
String id = "ASDFGT";
if (String(message) == id){
Serial.println("Strings are equal");
}
CodePudding user response:
The syntax of compareTo
is
myString.compareTo(myString2)
which returns:
- a negative number: if
myString
comes beforemyString2
- 0: if
myString
equalsmyString2
- a positive number: if
myString
comes aftermyString2
char message[dataSize];
String id = "ASDFGT";
if (String(message).compareTo(id) == 0)
{
Serial.println("Strings are equal");
}
The reference is here.
CodePudding user response:
Thanks to @mmixLinus there was a '\0' character at the end. Problem solved