20Oct/103
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
{
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
November 30th, 2010 - 23:09
teach me this
November 30th, 2010 - 23:47
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.
December 1st, 2010 - 00:29
i should of been Melanie instead of Ally…haha