3

私は今このような文字列の一部を取っています:

something.Substring(0, something.Length >= 8 ? 8 : something.Length)

その余分な混乱の唯一の理由は、長さがメソッドパラメータに入力したものよりも短い場合があり、これがエラーの原因となるためです。

テキストを安全にトリミングする簡単な方法はありますか?

4

5 に答える 5

16

ここでは醜い三元表現は本当に必要ありません。

return something.Substring(0, Math.Min(length, something.Length));
于 2012-06-02T19:13:04.787 に答える
7

string「混乱」を隠す拡張メソッドを記述します。

public static string SafeSubstring(this string orig, int length)
{
  return orig.Substring(0, orig.Length >= length ? length : orig.Length);
}

something.SafeSubstring(8);
于 2012-06-02T18:33:19.033 に答える
3

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);
    }
}
于 2012-06-02T18:47:49.353 に答える
0

これはこれを行うための最も効果的な方法ではありません。私はOdedのソリューションを使用しますが、これはあなたが探しているものを達成する方法でもあります。

new string(something.Take(8).ToArray());
于 2012-06-02T19:04:30.437 に答える
0

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);
}
于 2017-09-15T13:29:41.130 に答える