Skip to content

Instantly share code, notes, and snippets.

@tanaka-takayoshi
Created May 20, 2013 17:25
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaka-takayoshi/5613737 to your computer and use it in GitHub Desktop.
Save tanaka-takayoshi/5613737 to your computer and use it in GitHub Desktop.
C# で指定したエンコードで指定したバイト数"以下"に安全に文字列を切り詰めるメソッド。 1文字を2バイト以上で表現する場合、その途中のバイトで切り詰めずにより短くなるようにする。
public static class StringExtention
{
public static string LeftB(this string s, Encoding encoding, int maxByteCount)
{
var bytes = encoding.GetBytes(s);
if (bytes.Length <= maxByteCount) return s;
var result = s.Substring(0,
encoding.GetString(bytes, 0, maxByteCount).Length);
while (encoding.GetByteCount(result) > maxByteCount)
{
result = result.Substring(0, result.Length - 1);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment