Friday, May 11, 2007

Split string

Scenario:
The IC Number format is "770131-08-1234", and I need to split the text into 3 different sections, to display on the screen.

Solution:
There are many times we need to split a string with a delimiter.
The Split() function can help to deal with these cases easily.
Note that the delimiter is a character.

Example 1: Split with one delimiter
string stringToSplit = "770131-08-1234";
string[] splitStrings = stringToSplit.Split('-');

splitStrings[0] will be "770131".
splitStrings[1] will be "08".
splitStrings[2] will be "1234".

Example 2: Split with more than one delimiter
string stringToSplit = "770131;08-1234";
string[] splitStrings = stringToSplit.Split('-',';');

splitStrings[0] will be "770131".
splitStrings[1] will be "08".
splitStrings[2] will be "1234".

Example 3: Split without delimiter
Spaces will be treated as delimiter.
string stringToSplit = "770131 08 1234";
string[] splitStrings = stringToSplit.Split();

splitStrings[0] will be "770131".
splitStrings[1] will be "08".
splitStrings[2] will be "1234".

I've prepared a simple demonstration --> Split String
It's relatively slow compared to working on my own laptop.
Perhaps you can also download the source code here.
SplitString demo (SplitString.zip : 4.5KB)

No comments:

Post a Comment