Dot Net Perls

C# Equivalent of PHP explode Function

by Sam Allen

Problem

You want simple equivalents of the PHP explode function in C#. In PHP, explode splits a string on another string, while the str_split separates characters. Compare the PHP examples to C# .NET examples.

Solution: C# and PHP explode

First, I don't show complete replacements for explode here, as in C# your code logic would be structured differently. However, the general concept of explode is very easily matched in C#.

Example: the first PHP explode example

Take a look at the PHP.net website's first example on explode. This PHP code will, when in a PHP file, print out the two pizza slices. [PHP: explode Manual - php.net]

<?php
// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
?>

The C# equivalent here uses the Split method with the string[] array overload. When you need to use a string[] array to split strings, you must provide the StringSplitOptions enum. [C# - Split String Examples - dotnetperls.com]

using System;

class Program
{
    static void Main()
    {
        // Example 1
        string pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
        string[] pieces = pizza.Split(new string[] { " " },
            StringSplitOptions.None);
        Console.WriteLine(pieces[0]); // piece1
        Console.WriteLine(pieces[1]); // piece2
    }
}

Example: the second PHP explode example

Now we look at the second example from PHP, which uses a style of coding developers don't normally use in C#. It assigns 6 strings to the string array returned by explode.

In C#, you cannot access past the end of the array returned by Split, which means you cannot assign strings to array positions that don't exist.

<?php
// Example 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *
?>

The equivalent .NET program has to check the Length of the array before assigning each string. The code is much longer.

using System;

class Program
{
    static void Main()
    {
        // Example 2
        string data = "foo:*:1023:1000::/home/foo:/bin/sh";
        string[] s = data.Split(new string[] { ":" }, StringSplitOptions.None);
        string user = null;
        string pass = null;
        string uid = null;
        string gecos = null;
        string home = null;
        string shell = null;

        if (s.Length > 0)
        {
            user = s[0];
        }
        if (s.Length > 1)
        {
            pass = s[1];
        }
        if (s.Length > 2)
        {
            uid = s[2];
        }
        if (s.Length > 3)
        {
            gecos = s[3];
        }
        if (s.Length > 4)
        {
            home = s[4];
        }
        if (s.Length > 5)
        {
            shell = s[5];
        }
        Console.WriteLine(user); // foo
        Console.WriteLine(pass); // *
    }
}

The recommended solution in the C# version would be to use a class instance to store the six strings. This would give many potential advantages when you need to expand your application.

Information: what about the explode method with limit?

This is not available in C#, but a more complex method using Split with Join is possible. However, it would probably be easier to approach your problem a little differently, as with classes. This might also clarify your logic and error-checking.

Information: str_split in PHP

I was interested to find that str_split doesn't split in the same way as does Split in Perl and C#. It splits based on character counts, not delimeters. [PHP - str_split Manual - php.net]

To duplicate this functionality in C#, you could use ToCharArray() and a loop that counts characters. This would also give you more control, but would require more lines of code. [C# - Char Array Performance - dotnetperls.com]

Summary: using explode methods

We saw that many aspects of explode are readily available in C#. However, this article emphasizes the fundamental differences between scripting and compiled languages.

C# here has more lines of code, and much stricter error checking and exactness requirements. PHP, like Perl, is less strict and therefore shorter.

Which is better? It depends on your type of project. For larger, performance-critical projects with big development budgets and engineering teams, C# would be better, but for fast development and simplicity, PHP would win.

Dot Net Perls
About
Sitemap
Conversion
Convert Bytes to Megabytes
Convert Char Array to String
Convert Degrees Celsius to Fahrenheit
Convert Dictionary to String
Convert List to Array
New
Occurrence Count of String
StartsWith String Examples
© 2008 Sam Allen. All rights reserved.