Wednesday, October 22, 2008

.Net Equivalent of PHP's implode and explode function

Hi,

Lots of developers from PHP who study/migrate to ASP.Net have problems figuring out how would they implode an array of strings, or explode a string to array. Like me, this situation came out during my study in ASP.Net, I wondered what was the equivalent of PHP implode and explode function in .Net. And then I found out, that in .Net you can achieve this using the .Net's built-in string functions: Join function for implode, and string Split function for explode. To illustrate more, I make a sample code as shown below:

Type rest of the post here

///Assumed that you have two labels for display: lblColors, lblFruits
//****IMPLODE/JOIN****\\
//sample string of colors
string[] arrColors = {"red","orange","yellow","green","blue","indigo","violet"};

//implode/join the colors array using "and" and store it to a string variable
string strImplodedColors = String.Join(" and ", arrColors);
//display the imploded/joined to the colors label
this.lblColors.Text = "The colors of the rainbow are: " + strImplodedColors;


//****EXPLODE/SPLIT****\\
//sample string for comma-separated fruits
string strFruits = "avocado, apple, mango, grapes, banana";
//separator for the string
char[] separator = {','};
//explode/split the string and store it to a string array
string[] arrFruits = strFruits.Split(separator);
string strFavFruitDisplay = "Below are my top favorite fruits:
";
int i = 1;//iterator for counting display
//loop or iterate for each string in the exploded string
foreach(string strFruit in arrFruits)
{
//add each fruit to the display string
strFavFruitDisplay += i.ToString() + ". " + strFruit + "
";
i++;
}
//display the favorite fruits
this.lblFruits.Text = strFavFruitDisplay;

The above code is C#, if you want a VB version of it, just go to this URL: http://www.developerfusion.com/tools/convert/csharp-to-vb/

copy the code and convert it. It will allow you to easily convert C#.Net codes to VB.Net and vice versa.

Try it!

jjygot@gmail.com

No comments: