J'ai écrit cette extension de chaîne il y a quelque temps, et je commence à en tirer un peu parti.Une façon d'améliorer cette méthode de tranche de chaîne?
public static string Slice(this string str, int? start = null, int? end = null, int step = 1)
{
if (step == 0) throw new ArgumentException("Step cannot be zero.", "step");
if (start == null)
{
if (step > 0) start = 0;
else start = str.Length - 1;
}
else if (start < 0)
{
if (start < -str.Length) start = 0;
else start += str.Length;
}
else if (start > str.Length) start = str.Length;
if (end == null)
{
if (step > 0) end = str.Length;
else end = -1;
}
else if (end < 0)
{
if (end < -str.Length) end = 0;
else end += str.Length;
}
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((int)start, (int)(end - start));
int length = (int)(((end - start)/(float)step) + 0.5f);
var sb = new StringBuilder(length);
for (int i = (int)start, j = 0; j < length; i += step, ++j)
sb.Append(str[i]);
return sb.ToString();
}
Comme c'est dans tous mes projets maintenant, je me demande si j'aurais pu faire mieux. Plus efficace, ou produirait-il des résultats inattendus dans tous les cas?
Tranche. Cela fonctionne comme la notation de tableau de Python.
"string"[start:end:step]
De nombreuses autres langues ont quelque chose comme ça aussi. string.Slice(1)
est équivalent à string.Substring(1)
. string.Substring(1,-1)
enlève le premier et le dernier caractère. string.Substring(null,null,-1)
va inverser la chaîne. string.Substring(step:2)
retournera une chaîne avec tous les autres caractères ... également similaire à JS's slice mais avec un argument supplémentaire.
Re révisé en fonction de vos suggestions:
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.Value - 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();
}
Qu'est-ce qu'il censé faire? Je sais que je pourrais y arriver, mais je me sens un peu paresseux ... – ChrisF
est-ce la sous-chaîne !? – Fredou
Je suis intrigué de savoir à quoi vous l'utilisez? Le bit étape est intrigant. Je comprends ce qu'il fait, mais quelle est l'application pratique. Juste intéressé. –