I am trying to compare two strings but one of the string contains a white space at the end. I used Trim() and compared but didn't work because that white space is getting converted to %20 and I thing Trim does not remove that. it is something like "abc"
and "abc%20"
, what can I do in such situation to compare strings whih ignoring the case too?
You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
String comparison by Using String Library Functionstrcmp() function is used to compare two strings. The strcmp() function takes two strings as input and returns an integer result that can be zero, positive, or negative. The strcmp() function compares both strings characters.
In order to compare two strings, we can use String's strcmp() function. The strcmp() function is a C library function used to compare two strings in a lexicographical manner. The function returns 0 if both the strings are equal or the same. The input string has to be a char array of C-style string.
%20
is the url-encoded version of space.
You can't directly strip it off using Trim()
, but you can use HttpUtility.UrlDecode() to decode the %20
back to a space, then trim/do the comparison exactly as you would otherwise;
using System.Web;
//...
var test1 = "HELLO%20";
var test2 = "hello";
Console.WriteLine(HttpUtility.UrlDecode(test1).Trim().
Equals(HttpUtility.UrlDecode(test2).Trim(),
StringComparison.InvariantCultureIgnoreCase));
> true
Use HttpUtility.UrlDecode to decode the strings:
string s1 = "abc ";
string s2 = "abc%20";
if (System.Web.HttpUtility.UrlDecode(s1).Equals(System.Web.HttpUtility.UrlDecode(s2)))
{
//equals...
}
In case of WinForms or Console (or any non ASP.NET) project you will have to add reference to the System.Web
assembly in your project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With