C#
Rightの仕様差
出典: VB.net の Right / Mid / Left を C# に翻訳する完全早見表 — なぜ直訳は危険か:VB.netとC#の文字列インデックス仕様差 / Rightの仕様差
// NGパターン:直訳
string r = s.Substring(s.Length - 3); // "cde" だが s が短いと例外
string r2 = "ab".Substring("ab".Length - 5); // ArgumentOutOfRangeException
string r3 = ((string)null).Substring(((string)null).Length - 3); // NRE
▸ この snippet は実行結果未収録
▸ 実行結果は未収録です
Source収録記事
この snippet は記事の「なぜ直訳は危険か:VB.netとC#の文字列インデックス仕様差 / Rightの仕様差」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。
同じ記事から
6 件public static class StringCompat { /// <summary>VB.net の Right 相当。null・長さオーバーフロー・負値を吸収。</summary> public static string Right(string s, int length)未収録
ヘルパ1: RightのC#実装
#d3eb9db0ae6a
string r1 = StringCompat.Right("abcde", 3); // "cde" string r2 = StringCompat.Right("ab", 5); // "ab" string r3 = StringCompat.Right(null, 3); // ""未収録
ヘルパ1: RightのC#実装
#45fda6516d55
public static class StringCompat { /// <summary>VB.net の Mid 相当。1ベース起点、範囲外は空文字。</summary> public static string Mid(string s, int start, int length)未収録
ヘルパ2: MidのC#実装
#af9a11fd98ca
public static class StringCompat { /// <summary>VB.net の Left 相当。null・長さオーバーフロー・負値を吸収。</summary> public static string Left(string s, int length)未収録
ヘルパ3: LeftのC#実装
#33c0d3d82b20
public static string RightByGrapheme(string s, int length) { if (string.IsNullOrEmpty(s) || length <= 0) return string.Empty; var si = new System.Globalization.StringInfo(s);未収録
全角文字・Surrogate Pairで末尾が壊れる
#f3681c003f30
// バイト単位で取りたい場合(SJIS で固定長レコードを切る等) byte[] bytes = System.Text.Encoding.GetEncoding("Shift_JIS").GetBytes(s); byte[] slice = new byte[len]; Array.Copy(bytes, start, slice, 0, len);未収録
文字数vsバイト数の混乱
#3a5a69353075
