Monday 17 September 2012

CSharp: Slice in CSharp

Question:
Is there an equivalent to the Python slice method in c#?
How to slice in c#?


Answer:
You can use the Substring method of the String class or try a linq skip, take, concat approch.

Here is an example using Substring
/// 
/// Returns a save substring from index start to index end (excluded)
/// if the end index exceeds the length the the method returns only the remaining chars.
/// 
/// 
/// start index
/// end index, is an outer bound, easier to calculate
/// 
public static string Slice(this string gstr, int startIncluded, int endExcluded)
{
 string result = "";
 if(! string.IsNullOrEmpty(gstr) &&
  startIncluded <= endExcluded)
 {
  if (endExcluded > gstr.Length)
  {
   endExcluded = gstr.Length;
  }
  result = gstr.Substring(startIncluded, endExcluded - startIncluded);
 }
 return result;
}




No comments: