Skip to content

A Slice in C#, not literally

April 13, 2011

For writing my WP7 application, it had involved some string slicing, and because the code I had been looking at was Javascript where string slicing is fairly easy, doing this in C# was slightly trickier. However, having researched this, if you wanted to slice a C# string, the implementation is quite easy.

So what does it mean to string slice: –

By slicing a string, you can extract the characters from index one to index two, essentially calling Substring with two index values.

Although no framework exists, you can create an extension class that handles this.

public static class Extensions
{
    public static string Slice(this string source, int start, int end)
    {
        if (end < 0) // Keep this for negative end support
        {
            end = source.Length + end;
        }
        int len = end – start;               // Calculate length
        return source.Substring(start, len); // Return Substring of length
    }
}

Quintessentially, you pass a start index, which is >- 0 and second parameter can be an integer, which is takes a substring of that string as its index, if it is negative, you start from the end and count backwards, if you want to go to the end, its the length of the string minus one.

E.g.

string s = "Hello World!";
Console.WriteLine(s.Slice(0, 1));  // First chars Console.WriteLine(s.Slice(0, 2));  // First two chars
Console.WriteLine(s.Slice(1, 2));  // Second char Console.WriteLine(s.Slice(8, 11)); // Last three chars
 
Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: