Saturday, December 14, 2013

C# split string using \ slash

If you are doing C# coding and need to split a string like this "ABC\0\0\0\0", you may be interested to read this post. If you have decided to continue reading, let's the code speak its all.

String a = @"ABC\0\0\0\0"; // Or "ABC\\0\\0\\0\\0"
String[] result = a.Split('\\');

We will be expecting the result array length is 5 with value result[0] ="ABC", result[1] to result[4] =  "0" and that's the result we will be getting.

Look at another case below.

String a1 = "ABC\0\0\0\0";
String[] result1 = a.Split('\\');

Are you expecting the same result ? If you are, you will be disappointed that no split has took place at all. You will get result1 array length is 1 and result1[0] = "ABC\0\0\0\0".

For a1, the \0 is treated as special character due to the single slash and no @ in front of the string. Sometimes you have no control on all source code, you may got a1 from another assembly that you have no source code access and no way to change the source code. 

If you are interested to get the value ABC and doesn't really care about what's after ABC, use below instead.
String a2 = "ABC\0\0\0\0";
String[] result2 = a.Split('\0');

You will be getting result2 with length of 5, result2[0]="ABC", result1[1] to result[4] are empty string. Yes, of course, you may provide options to Split method to remove empty entries.

Well, of course a2.Substring(0, 3) will also return you "ABC". But what if you encounter a string "ABCDVariableLength\0\0\0\0\0", then you may still want to use the split. 

Alternatively, use IndexOf('\0') which looks like this:
String a3 ="ABCDVariableLength\0\0\0\0\0";
String front = a3.Substring(0, a3.IndexOf('\0'));

Alternatively, use IndexOf("\0") or a1.Split(new String[] {"\0"}, StringSplitOptions.RemoveEmptyEntries), it works in my PC, although I thought it shouldn't.

Using IndexOf("\") will return -1 due to the same special character reason. 

Happy coding :)