Created
May 20, 2013 17:25
-
-
Save tanaka-takayoshi/5613737 to your computer and use it in GitHub Desktop.
C# で指定したエンコードで指定したバイト数"以下"に安全に文字列を切り詰めるメソッド。 1文字を2バイト以上で表現する場合、その途中のバイトで切り詰めずにより短くなるようにする。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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