Serial input string equals another string not working

I ran into a problem while writing an if statement that compares 2 lines

String str1 = Serial.ReadLine(); //The serial reads "R_011"
str1.Trim();

if(str1 == "R_011"){
  //Action
}

This does not work as it interprets that both lines are different.

I realized that if I replace the Serial input with a string, I compare it with

str1 = "R_011";

it works fine, so it must be something related to what Serial reads.

Can anybody help me? Thank.

+4
source share
2 answers

When you call Trim(), it returns a new line. Set the result by reference str1. Try also using the method Equalsand parameter StringComparisonto ignore case. Try the following:

string str1 = Serial.ReadLine(); 
str1 = str1.Trim();

if (str1.Equals("R_011", StringComparison.OrdinalIgnoreCase))
{
  //Action
}
+7
source

String, :

if(Convert.ToString(str1) == "R_011"){

// }

-2

Source: https://habr.com/ru/post/1674003/


All Articles