Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparison ==, when it ignores white spaces

I have the following method inside my asp.net mvc web application, to check if an ip address already exists or not:-

public bool ISTMSIPUnique(string ip, int? id=0) 
{
    var technology = FindTechnology(id.Value);
    var result = tms.TechnologyIPs.Where(a.IPAddress.ToUpper() == ip.ToUpper());
    return (result.Count() == 0);
}

But I have noted that the a.IPAddress.ToUpper() == ip.ToUpper() will do the following:-

  1. It will assume that “test” and “test ” are the same. (it will ignore white spaces at the end of the character).
  2. But will assume that the “test” and “ test ”, white space to the left and to the right are two different strings.

So what is the rule behind this? Should I always trim() the string before saving it to the SQL server DB to overcome this problem Since IP addresses can not contain whitespace?

like image 380
john Gu Avatar asked Jan 13 '23 02:01

john Gu


2 Answers

Since you posted the detail that this is actually using EF, my comment regarding string comparisons isn't valid.

Assuming your database is Sql Server, or any database that conforms to ANSI standards for string comparisons, strings are padded to be the same length before comparison. So 'test' is padded to be the same length as 'test ', by appending a white space character, before the strings are compared, thus they evaluate as equal. Conversely when comparing 'test' and ' test', 'test' is padded to 'test ' to be the same length as ' test', which still results in the strings not comparing as equivalent.

http://support.microsoft.com/kb/316626

like image 133
Preston Guillot Avatar answered Jan 19 '23 23:01

Preston Guillot


Definitely "test" and "test " are different strings. Framework never ignores spaces.

I would save trimmed string into the database. Also I would suggest to use string.Equals for strings comparison.

BTW if you are working with ip addresses, why do you need to call ToUpper method?

I suggest to read this article. It is about string intern pool. http://msdn.microsoft.com/en-us/library/system.string.intern.aspx. Very useful!

The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system. For example, if you assign the same literal string to several variables, the runtime retrieves the same reference to the literal string from the intern pool and assigns it to each variable.

like image 24
Andrei Avatar answered Jan 19 '23 23:01

Andrei