Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Empty in strings

2 days ago, there was a question related to string.LastIndexOf(String.Empty) returning the last index of string:

Do C# strings end with empty string?

So I thought that; a string can always contain string.empty between characters like:

"testing" == "t" + String.Empty + "e" + String.Empty +"sting" + String.Empty;

After this, I wanted to test if String.IndexOf(String.Empty) was returning 0 because since String.Empty can be between any char in a string, that would be what I expect it to return and I wasn't wrong.

string testString = "testing";
int index = testString.LastIndexOf(string.Empty); // index is 6
index = testString.IndexOf(string.Empty); // index is 0

It actually returned 0. I started to think that if I could split a string with String.Empty, I would get at least 2 string and those would be String.Empty and rest of the string since String.IndexOf(String.Empty) returned 0 and String.LastIndexOf(String.Empty) returned length of the string.. Here is what I coded:

string emptyString = string.Empty;
char[] emptyStringCharArr = emptyString.ToCharArray();
string myDummyString = "abcdefg";
string[] result = myDummyString.Split(emptyStringCharArr);

The problem here is, I can't obviously convert String.Empty to char[] and result in an empty string[]. I would really love to see the result of this operation and the reason behind this. So my questions are:

  1. Is there any way to split a string with String.Empty?

  2. If it is not possible but in an absolute world which it would be possible, would it return an array full of chars like [0] = "t" [1] = "e" [2] = "s" and so on or would it just return the complete string? Which would make more sense and why?

like image 802
Pabuc Avatar asked Jan 12 '11 08:01

Pabuc


1 Answers

Yes, you can split any string with string .Empty

 string[] strArr = s.Split(string.Empty.ToCharArray());
like image 150
AsifQadri Avatar answered Oct 28 '22 03:10

AsifQadri