中文字的padLeft 或 padRight
今天遇到的問題,做個記錄。
/// <summary>
/// 中文字截字,不足補字串
/// </summary>
/// <param name="org">原始字串</param>
/// <param name="RL">靠右靠左補 R(靠右) L(靠左)</param>
/// <param name="sLen">長度</param>
/// <param name="padStr">替代字元</param>
/// <returns></returns>
static string CHT_WordPadLeftRight(string org, string RL, int sLen, char padStr)
{
var sResult = "";
//計算轉換過實際的總長
int orgLen = 0;
int tLen = 0;
for (int i = 0; i < org.Length; i++)
{
string s = org.Substring(i, 1);
int vLen = 0;
//判斷 asc 表是否介於 0~128
if (Convert.ToInt32(s[0]) > 128 || Convert.ToInt32(s[0]) < 0)
{
vLen = 2;
}
else
{
vLen = 1;
}
orgLen += vLen;
if (orgLen > sLen)
{
orgLen -= vLen;
break;
}
sResult += s;
}
//計算轉換過後,最後實際的長度
tLen = sLen - (orgLen - org.Length);
if (RL == "R")
{
return sResult.PadLeft(tLen, padStr);
}
else
{
return sResult.PadRight(tLen, padStr);
}
}