首页 新闻 赞助 找找看

有没有什么办法妥当处理中英文混合的字数截取,英文一个单词的长度为1

0
悬赏园豆:15 [待解决问题]

有没有什么办法妥当处理中英文混合的字数截取,比如:

Hello world,你好,Hello world,你好!   这个字符串的总长度为12,标点符号也计入长度。截取4个字符的 结果应是:Hello world,你

泪的诺言lni的主页 泪的诺言lni | 初学一级 | 园豆:105
提问于:2011-01-12 11:20
< >
分享
所有回答(3)
0

你这个是截取4个字,不是4个字符,你要先分词,然后再截取。

eaglet | 园豆:17139 (专家六级) | 2011-01-12 12:58
0

static void Main(string[] args)
{
string str = "Hello world,你好,Hello world,你好!";
Console.WriteLine(strOperation(str,
4));
Console.Read();
}
public static string strOperation(string str,int count)
{
Regex re
= new Regex(@"[a-zA-Z]+");
Match mc
= re.Match(str);
List
<string> wordarr = new List<string>();
if (mc.Success)
{
MatchCollection mcs
= re.Matches(str);
if (mcs.Count > 0)
{
for (int i = 0; i < mcs.Count; i++)
{
str
=str.Replace(mcs[i].Value, i.ToString());
wordarr.Add(mcs[i].Value);
}
}
}
str
=str.Replace(" ", "").Substring(0,count);
for (int i = 0; i < count; i++)
{
if (str.Contains(i.ToString()))
{
str
= str.Replace(i.ToString(), " "+wordarr[i]);
}
}
return str.Trim();
}

 

按你的要求写出来了,但感觉你的需求有点问题,”Hello world,你“这个应该是五个字符,还有一个空格。

artwl | 园豆:16736 (专家六级) | 2011-01-12 12:59
0

中英文编码方式是不一样的,一个是1字节,一个是2字节。

massinger | 园豆:706 (小虾三级) | 2011-01-12 13:48
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册