请各位大虾指教:C#中如何判断输入的字符串中是否有汉字??

tuzibai 2009-03-20 08:43:56
我在学习C#的过程中,刚学完哈希表,可后有一个题:判断用户输入的字符串中有几个汉字》》??
看到这里我都晕了,怎么判断是汉字呢?
我是初学者,请各位大虾指教……
...全文
367 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
zcdg909 2009-03-21
  • 打赏
  • 举报
回复
.net中有直接判断的函数,查msdn
surlew 2009-03-21
  • 打赏
  • 举报
回复
学习
crystalsky21504119 2009-03-21
  • 打赏
  • 举报
回复
根据中文字符的范围判断控制
kbtjh 2009-03-21
  • 打赏
  • 举报
回复
帮顶一下,,
oak_l 2009-03-20
  • 打赏
  • 举报
回复
可以用正则表达式。
判断字符串是否为连续的中文字符(不包含英文及其他任何符号和数字)的正则表达式为:"^[\u4e00-\u9fa5]+$".
using System;
using System.Text.RegularExpressions;
//regexp规则类包含在System.Text.RegularExpressions.dll文件中,在对应用软件进行编译时你必须引用这个文件


namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string test = Console.ReadLine();
string chinese = "";
int num=0;
Regex rx = new Regex(@"^[\u4e00-\u9fa5]+$");


//IsMatch: Regex类中的静态方法,如果表达式在字符串中匹配,该方法返回一个布尔值;
foreach(char ch in test)
{
if(rx.IsMatch(ch.ToString()))
{
num++;
chinese += ch.ToString();
}
}

if (num == 0)
Console.WriteLine("输入中没有汉字。");
else
Console.WriteLine("输入中有汉字"+num+"个:"+chinese);

Console.ReadKey();
}
}
}
gisyellow 2009-03-20
  • 打赏
  • 举报
回复
使用如下函数获取字符串的长度,只需检查该字符串长度是否为strData.Length即可,如果是,那么就没有中文字符,否则就可能有。
private int GetGBLength(string strData)
{
int iLen = 0;
if (strData != null)
{
iLen = strData.Length;
byte[] byteData = new byte[iLen * 2];
try
{
iLen = Encoding.Default.GetBytes(strData, 0, strData.Length, byteData, 0);
}
catch { }
}
return iLen;
}
liusichen_0 2009-03-20
  • 打赏
  • 举报
回复

方法一
在unicode 字符串中,中文的范围是在4E00..9FFF:CJK Unified Ideographs。

通过对字符的unicode编码进行判断来确定字符是否为中文。

protected bool IsChineseLetter(string input,int index)
...{ int code = 0;
int chfrom = Convert.ToInt32("4e00", 16); //范围(0x4e00~0x9fff)转换成int(chfrom~chend)
int chend = Convert.ToInt32("9fff", 16);
if (input != "")
...{
code = Char.ConvertToUtf32(input, index); //获得字符串input中指定索引index处字符unicode编码

if (code >= chfrom && code <= chend)
...{
return true; //当code在中文范围内返回true

}
else
...{
return false ; //当code不在中文范围内返回false
}
}
return false;
}




http://hi.baidu.com/song70/blog/item/011183440bd6408ab3b7dcd3.html
whowhen21 2009-03-20
  • 打赏
  • 举报
回复
给你提供个思路哦,自己再研究研究哈:
public double GetLength(string p_Text) 
{
double _Count = 0;
for (int i = 0; i != p_Text.Length; i++)
{
if (p_Text[i] > 255) //汉字一定大于255
{
_Count += 2;
}
else
{
if (p_Text[i] >= 65 && p_Text[i] <= 90)
{
_Count++; //26个大写字母
}
else
{
_Count += 0.5;
}

}
}

return _Count;
}
mohugomohu 2009-03-20
  • 打赏
  • 举报
回复
不知道啊,可能根据ASCII码判断吧

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧