String 字符串比较不起作用

String 字符串比较不起作用,string,arduino-uno,String,Arduino Uno,有人能解释一下这个代码有什么问题吗。为什么if语句在匹配精确的字符串时总是为false..我也用==尝试过..但是,每次都没有找到匹配项 String inData = ""; char inChar; String property; String a = "test"; void loop() { Serial.println("String Comparison"); if(Serial.available() > 0){ while(Seri

有人能解释一下这个代码有什么问题吗。为什么if语句在匹配精确的字符串时总是为false..我也用==尝试过..但是,每次都没有找到匹配项

String inData = "";
char inChar;
String property;  
String a = "test";

void loop() {


  Serial.println("String Comparison"); 

  if(Serial.available() > 0){

        while(Serial.available()>0) {
          inChar = Serial.read();
          inData.concat(inChar);
        }

        //Extracting Property
        property = inData.substring(inData.lastIndexOf(":")+2); // Extracts the String "test"
        Serial.println("Property:" +property);


        if(property.equals(a)){ // It never matches though, it is TRUE all the time

           Serial.println(" Matched !! ");

        }      
        else
        Serial.println(" Match Not Found !! ");

       inData = "";


   }

  delay(5000);
}

因为我能够看到匹配和未命中,我想我需要更多的信息来复制错误

因为我没有看到它发生,我猜它与输入是什么以及这行如何解析它有关

property = inData.substring(inData.lastIndexOf(":")+2); // Extracts the String "test"
  • 失败的当前输入是什么
  • 你能把你的打印输出和输入一起包括进去吗
  • 添加一行以打印出
    property.length()
    以测试隐藏的空白字符

我也遇到了这个问题,实际上字符串长度不匹配。我通过添加:
command=command.substring(0,command.length()-1)解决了这个问题在您的情况下,您可能可以通过执行+1而不是+2来修复它。