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?
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.
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.
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.
the initializations are the same: the ctor of std::string sets it to the empty string.
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 ("");
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))
{
}
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