私は今このような文字列の一部を取っています:
something.Substring(0, something.Length >= 8 ? 8 : something.Length)
その余分な混乱の唯一の理由は、長さがメソッドパラメータに入力したものよりも短い場合があり、これがエラーの原因となるためです。
テキストを安全にトリミングする簡単な方法はありますか?
ここでは醜い三元表現は本当に必要ありません。
return something.Substring(0, Math.Min(length, something.Length));
string
「混乱」を隠す拡張メソッドを記述します。
public static string SafeSubstring(this string orig, int length)
{
return orig.Substring(0, orig.Length >= length ? length : orig.Length);
}
something.SafeSubstring(8);
Visual Basicは、Right()およびLeft()文字列関数を実装しています。それらを盗むかもしれませんが、それらは十分にテストされています:
public static class Extensions {
public static string Right(this string str, int Length) {
if (Length < 0) throw new ArgumentOutOfRangeException("Length");
if (Length == 0 || str == null) return string.Empty;
int len = str.Length;
if (Length >= len) return str;
else return str.Substring(len - Length, Length);
}
public static string Left(this string str, int Length)
{
if (Length < 0) throw new ArgumentOutOfRangeException("Length");
if (Length == 0 || str == null) return string.Empty;
int len = str.Length;
if (Length >= len) return str;
else return str.Substring(0, Length);
}
}
これはこれを行うための最も効果的な方法ではありません。私はOdedのソリューションを使用しますが、これはあなたが探しているものを達成する方法でもあります。
new string(something.Take(8).ToArray());
Hans Passantの回答に触発されて、 VisualBasicの実装を「盗む」ためのより直接的な方法があります。(このアプローチでは、Microsoft.VisualBasic.dllへの参照を追加する必要があります)
public static class Extensions
{
public static string Right(this string str, int Length) =>
Microsoft.VisualBasic.Strings.Right(str, Length);
public static string Left(this string str, int Length) =>
Microsoft.VisualBasic.Strings.Left(str, Length);
}