TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# String Slice

This C# article provides a Slice extension method on the string type.

String slice. A string can be sliced.

No Framework method exists. We provide a custom extension method. By slicing a string, we extract the characters from index one to index two. This is essentially the same as calling Substring with two index values.

Function/Input/Output

Slice(1,4)    Peaceful                  eac
Slice(3,-2)   The morning is upon us.    morning is upon u

Example. With the JavaScript slice method, you pass it the start index, which must always be >= 0. The second parameter can be any integer. When it is negative, it means you start from the end and then count backwards.

Note: In JavaScript you can omit the second parameter. To duplicate this, create an overload that uses Length - 1 as the second parameter.

C# program that slices strings

using System;

class Program
{
    static void Main()
    {
	//
	// Tests from Mozilla
	//
	Console.WriteLine("Peaceful".Slice(1, 4));
	// eac
	Console.WriteLine("The morning is upon us.".Slice(3, -2));
	// " morning is upon u"

	string s = "0123456789_";
	//
	// These slices are valid:
	//
	Console.WriteLine(s.Slice(0, 1));  // First char
	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
    }
}

public static class Extensions
{
    /// <summary>
    /// Get the string slice between the two indexes.
    /// Inclusive for start index, exclusive for end index.
    /// </summary>
    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
    }
}

Output

eac
 morning is upon u
0
01
1
89_

The first character of the second test, which is similar to the Mozilla test, shows the first character as a space. My interpretation is that this is correct. The space is at index 3, while "m" is index 4.

This is an extension method—a method that can be used with syntax as though it were on the string class. To create an extension method, simply use the this keyword as the first parameter in a static method, which is in a static class.

Static ClassExtension Method

The required input and output above is adapted from the Mozilla Developer Center, which has documentation on JavaScript. To this end, we will have a Slice method equivalent to the JavaScript slice method.

Mozilla Developer Center

Correct? An earlier implementation of Slice shown on this article was incorrect when handling the end parameter. The article was corrected based on the changes noted in the array slice article on this site.

Array Slice

Summary. Here we saw an implementation of the Slice method in the C# programming language. The code here is an extension method, which provides very simple syntax for callers. We used the extension method because it makes the syntax clearer.

However: In some projects it would be better to use a normal static method. But Slice is useful enough to warrant an extension method.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf