문자열 캡처, 한 중국어에 두 문자 계산
3804 단어 C# 문자열 절취
//
public static string LeftStr(string str, int len)
{
if (str.Length == 0) return str;
ASCIIEncoding ascii = new ASCIIEncoding();
int tempLen = 0;
string tempString = "";
byte[] s = ascii.GetBytes(str);
for (int i = 0; i < s.Length; i++)
{
if ((int)s[i] == 63)
{
tempLen += 2;
}
else
{
tempLen += 1;
}
try
{
tempString += str.Substring(i, 1);
}
catch
{
break;
}
if (tempLen > len)
break;
}
return tempString;
}
코드 2
//
public static string Cut_Str(String iStr,int len,String ended) {
if (String.IsNullOrEmpty(iStr)) return String.Empty;
byte[] bytes = Encoding.Unicode.GetBytes(iStr);
int j = 0;
int i = 0;
for (; i < bytes.Length && j < len; i++) {
if (i % 2 == 0)
j++;
else if (bytes[i] > 0) //
j++;
}
if (i % 2 == 1) {
if (bytes[i] > 0)
i--;
else
i++;
}
if (j <= (len - 1)) ended = String.Empty;
return Encoding.Unicode.GetString(bytes, 0, i) + ended;
}