C # how to compare two strings that have matching letters but they have spaces
Here is my code below, how can I make if
return true as it is currently missing a statement if
because there is a space in the string values.
string instrucType = "FM";
string tenInstrucType = "FM ";
if (tenInstrucType.Equals(instrucType))
{
blLandlordContactNumberHeader.Visible = true;
lblLandlordContactNumber.Text = landlordData.LandlordContact.DefPhone;
lblLandlordEmailHeader.Visible = true;
lblLandlordEmail.Text = landlordData.LandlordContact.DefEmail;
}
+3
ife labolz
source
to share
5 answers
Use the Trim function:
if (tenInstrucType.Trim().Equals(instrucType.Trim()))
This will only trim off the ends. If there is an option in the middle, use Replace.
+4
jpsnow72
source
to share
If the space is only at the end of the line, trim both lines:
if (tenInstrucType.Trim().Equals(instrucType.Trim()))
If you want to ignore all whitespace characters, you can remove them from the string:
string normalized1 = Regex.Replace(tenInstrucType, @"\s", "");
string normalized2 = Regex.Replace(instrucType, @"\s", "");
if (normalized1 == normalized2) // note: you may use == and Equals(), as you like
{
// ....
}
+1
Nemanja boric
source
to share
Try the following condition:
if (tenInstrucType.Replace(" ",string.Empty).Equals(instrucType.Replace(" ",string.Empty))
0
Andrey Gordeev
source
to share
Trim lines:
if (tenInstrucType.Trim().Equals(instrucType.Trim()))
0
Rui jarimba
source
to share
if (tenInstrucType.Replace(" ","").Equals(instrucType.Replace(" ","")))
using Trim
might seem right for this case, but note that it Trim
only removes leading or trailing spaces; interior spaces are not removed.
0
daryal
source
to share