Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle %20 while string comparison in c#

Tags:

string

c#

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?

like image 757
patel Avatar asked Jun 05 '13 07:06

patel


People also ask

Can I use == to compare strings in C?

You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.

Can you use == when comparing strings?

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.

How do I compare two strings in C?

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.

Can you compare strings in C?

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.


2 Answers

%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
like image 169
Joachim Isaksson Avatar answered Oct 26 '22 21:10

Joachim Isaksson


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.

like image 5
Shadow Wizard Hates Omicron Avatar answered Oct 26 '22 23:10

Shadow Wizard Hates Omicron