Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for string contents? string Length Vs Empty String

Which is more efficient for the compiler and the best practice for checking whether a string is blank?

  1. Checking whether the length of the string == 0
  2. Checking whether the string is empty (strVar == "")

Also, does the answer depend on language?

like image 288
Haydar Avatar asked Aug 13 '08 19:08

Haydar


People also ask

Does an empty string have a length?

An empty string is a String object with an assigned value, but its length is equal to zero. A null string has no value at all.

How do you test that a string str is the empty string?

String arrays can contain both empty strings and missing values. Empty strings contain zero characters and display as double quotes with nothing between them ( "" ). You can determine if a string is an empty string using the == operator.

Is it better to use or string empty?

Therefore you should always use string. The compiler will "link" them all to an empty string. I read somewhere (sorry, I don't remember where) that the empty string is duplicated once in each assembly. So each assembly that uses "" instead of System. String.


1 Answers

Yes, it depends on language, since string storage differs between languages.

  • Pascal-type strings: Length = 0.
  • C-style strings: [0] == 0.
  • .NET: .IsNullOrEmpty.

Etc.

like image 196
Stu Avatar answered Sep 20 '22 15:09

Stu