String Slice

Here’s an extension method to slice strings in C#, similar to Python’s slice notation.

public static string Slice(this string str, int? start = null, int? end = null, int step = 1)
{
    if (step == 0) throw new ArgumentException("Step size cannot be zero.", "step");

    if (start == null) start = step > 0 ? 0 : str.Length - 1;
    else if (start < 0) start = start < -str.Length ? 0 : str.Length + start;
    else if (start > str.Length) start = str.Length;

    if (end == null) end = step > 0 ? str.Length : -1;
    else if (end < 0) end = end < -str.Length ? 0 : str.Length + end;
    else if (end > str.Length) end = str.Length;

    if (start == end || start < end && step < 0 || start > end && step > 0) return "";
    if (start < end && step == 1) return str.Substring(start.Value, (end - start).Value);

    var sb = new StringBuilder((int)Math.Ceiling((end - start).Value / (float)step));
    for (int i = start.Value; step > 0 && i < end || step < 0 && i > end; i += step)
        sb.Append(str[i]);
    return sb.ToString();
}

"Hello World".Slice(1, -1); // ello Worl
"Hello World".Slice(null, null, -1); // dlroW olleH
Posted in

4 thoughts on “String Slice

  1. How to slice strings? I think you have to learn C# first. I’ll teach you on Saturday…we’ll see how long you last before falling asleep.

  2. Here is what I came up with: public int countAbc(String str) { if(str.length() < 3) reutrn 0; if(str.substring(0,3).equals(“abc”) || str.substring(0,3).equals(“aba”)){ reutrn 1 + countAbc(str.substring(1)); } else reutrn countAbc(str.substring(1));}

Leave a Reply

Your email address will not be published. Required fields are marked *