When I try this code, nothing happens (the message "Equal" should constantly be printed. There seems to occur an error. The stange thing is that this example is copied from the wiring documentation (see link)
#include <WString.h> // include the String library
String str1 = "CCCP";
String str2 = "CCCP";
// Tests to see if str1 is equal to str2
void setup() {
Serial.begin(9600);
}
void loop() {
if(str1.equals(str2) == true) {
Serial.println("Equal"); // They are equal so this line will print
}
else {
Serial.println("Not equal");
}
}
When I try this code, everything works fine:
String str1 = "CCCP";
char str3[] = "CCCP";
// Tests to see if str1 is equal to str3
void setup() {
Serial.begin(9600);
}
void loop() {
if(str1.equals(str3) == true) {
Serial.println("Equal"); // They are equal so this line will print
}
else {
Serial.println("Not equal");
}
}
Is is not possible to declare the string that is compared as string, but only as char in Arduino?
#include <WString.h>
String str1 = "CCCP";
char str3[] = "CCCP";
String Test = "CCCP";
// Tests to see if str1 is equal to str3
void setup() {
Serial.begin(9600);
}
void loop() {
if(str1.equals(str3) == true) {
Serial.println("Equalstr3"); // They are equal so this line will print
}
else {
Serial.println("Not equal");
}
delay(1000);
if(str1.equals(Test) == true) { // Testing directly
Serial.println("EqualTest"); // They are equal so this line will print
}
else {
Serial.println("Not equal");
}
delay(2000);
}
The code uploads without any problems. When I open the serial monitor I get the message for the first If....Then ( prints "Equalstr3"), but for the next If....Then nothing happens.
No messages are printed anymore, so the program hangs at the second If....Then.
Maybe I have to contact the person who wrote this library. Maybe this is not possible.
I really liked the idea of comparing two stings because I want to compare the content of several strings.
that's not even a function, that's just how C works, a string is absolutely NO DIFFERENT from an array, except that it is null terminated to indicate where it ends.
all WString.h does is be a wrapper for string.h and stdlib.h
const char * is how you declare a string, char * is the pointer , and the const tells the compiler not to expect this pointer to move, by knowing that the pointer won't move around, the compiler can allocate the memory during compile time (as opposed to using malloc() and calloc() which has to place the pointer to a location with enough free space during run time).
const char * str = "abc";
is identical to
char str[4] = {'a', 'b', 'c', 0};
and
volatile int length = 4; // volatile to avoid optimization
char str[length];
just so you can relate pointers to arrays, which you are probably more familiar with
I'm just a guy who'd sacrifice convenience for code size. Also I would hate to run into heap-stack crashes because of somebody else's mistake, with a library like WString, you'd have a tendency to assume that it's reliable