using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace DataSync
{
public class WordHelper
{
[DllImport("kernel32.dll", EntryPoint = "LCMapStringA")]
public static extern int LCMapString(int locale, int dwMapFlags, byte[] lpSrcStr, int cchSrc, byte[] lpDestStr, int cchDest);
public static string ToTraditionalChinese(string source)
{
return ToTraditional(source, 0x04000000);
}
public static string ToSimplifiedChinese(string source)
{
return ToTraditional(source, 0x02000000);
}
public static string ToTraditional(string source, int type)
{
byte[] srcByte = Encoding.Default.GetBytes(source);
byte[] desByte = new byte[srcByte.Length];
LCMapString(2052, type, srcByte, -1, desByte, srcByte.Length);
string des = Encoding.Default.GetString(desByte);
return des;
}
public static bool IsChinese(string word)
{
char[] chars = word.ToCharArray();
foreach (var c in chars)
{
if (!(c >= 0x4e00 && c <= 0x9fbb))
return false;
}
return true;
}
public static string Substring(string text, int maxLength)
{
if (string.IsNullOrEmpty(text))
return string.Empty;
StringBuilder stringBuilder = new StringBuilder();
bool surrogate;
int index = 0;
int count = 0;
foreach (char item in text)
{
if (index >= maxLength)
break;
surrogate = char.IsSurrogate(item);
if (surrogate)
{
count++;
if (count > 1)
count = 0;
}
stringBuilder.Append(item);
index++;
}
if (count == 1)
{
char lastChar = text[index++];
stringBuilder.Append(lastChar);
}
return stringBuilder.ToString();
}
}
}