Skip to content

Instantly share code, notes, and snippets.

@tomzorz
Created November 18, 2019 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomzorz/ee4f383f571e824d5ea08004862f52d2 to your computer and use it in GitHub Desktop.
Save tomzorz/ee4f383f571e824d5ea08004862f52d2 to your computer and use it in GitHub Desktop.
various C# / .net implementations of a custom substring function
using System;
using System.Linq;
using System.Text;
namespace MySubstring
{
// ReSharper disable once ClassNeverInstantiated.Global
public class Program
{
// ReSharper disable once UnusedParameter.Global
public static void Main(string[] args)
{
const string hello = "Hello World!";
Console.WriteLine($"original: {hello}");
Console.WriteLine($"solution 1: {hello.MySubstring1(6)}; {hello.MySubstring1(8, 3)}");
Console.WriteLine($"solution 2: {hello.MySubstring2(6)}; {hello.MySubstring2(8, 3)}");
Console.WriteLine($"solution 3: {hello.MySubstring3(6)}; {hello.MySubstring3(8, 3)}");
Console.WriteLine($"solution 4: {hello.MySubstring4(6)}; {hello.MySubstring4(8, 3)}");
Console.WriteLine($"solution 5: {hello.MySubstring5(6)}; {hello.MySubstring5(8, 3)}");
Console.ReadLine();
}
}
public static class Implementations
{
// using built-in feature
public static string MySubstring1(this string s, int a, int? b = null) => b.HasValue ? s.Substring(a, b.Value) : s.Substring(a);
// new C# 8.0 indices / ranges with return type enforcing .ToString() on the ReadOnlySpan<char> which is special as it gives a string back
public static string MySubstring2(this string s, int a, int? b = null) => b.HasValue ? s[a..(a+b.Value)] : s[a..];
// same but condensed with null coalescing
public static string MySubstring3(this string s, int a, int? b = null) => s[a..(a+b ?? ^0)]; // I ♥ this
// linq magic
public static string MySubstring4(this string s, int a, int? b = null) => string.Concat(b.HasValue ? s.Skip(a).Take(b.Value).ToArray() : s.Skip(a).ToArray());
// ye olden for loop with StringBuilder
public static string MySubstring5(this string s, int a, int? b = null)
{
var sb = new StringBuilder();
for (var i = a; i < (a + b ?? s.Length); i++) sb.Append(s[i]);
return sb.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment