Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialised string seems to contain string.Empty [duplicate]

I jumped into this accidentally and have no clue as to why this is happening

string sample = "Hello World";
if (sample.Contains(string.Empty))
{
    Console.WriteLine("This contains an empty part ? at position " + sample.IndexOf(string.Empty));
    Console.WriteLine(sample.LastIndexOf(string.Empty));
    Console.WriteLine(sample.Length);
}

Output

This contains an empty part ? at position 0

10

11

I am happy with the last part, but i have no idea why this is evaluated true. Even Indexof and LastIndexOf have separate values.

Could anyone help me out on why is this so?

EDIT

I believe this is a bit relevant to my question and would be also helpful to those who stumble upon this question.

See this SO link: Why does "abcd".StartsWith("") return true?

like image 355
V4Vendetta Avatar asked May 04 '11 11:05

V4Vendetta


People also ask

How do you initialize an empty string?

To initialize an empty string in Python, Just create a variable and don't assign any character or even no space. This means assigning “” to a variable to initialize an empty string.

How do you initialize a string?

Initialize a string by passing a literal, quoted character array as an argument to the constructor. Initialize a string using the equal sign (=). Use one string to initialize another. These are the simplest forms of string initialization, but variations offer more flexibility and control.

Can we initialize string?

As we all know String is immutable in java so do it gives birth to two ways of initialization as we do have the concept of String Pool in java. In this method, a String constant object will be created in String pooled area which is inside the heap area in memory.

Is std::string initialized to empty?

the initializations are the same: the ctor of std::string sets it to the empty string.


2 Answers

From msdn for IndexOf

If value is String.Empty, the return value is 0.

For LastIndexOf

If value is String.Empty, the return value is the last index position in this instance.

For Contains

true if the value parameter occurs within this string, or if value is the empty string ("");

like image 187
SwDevMan81 Avatar answered Nov 14 '22 22:11

SwDevMan81


Question: Does the string "Hello World" contain String.Empty?

Answer: Yes.

Every possible string contains String.Empty, so your test is correctly returning true.

If you are trying to test if your string is empty, then the following code is what you want

if (string.IsNullOrEmpty(sample)) 
{

}
like image 41
RB. Avatar answered Nov 14 '22 21:11

RB.