vb.net如何判断一个字符串中是否包含汉字?
下面这个是vb6的,直接用会报错,我也不知道怎么转为.net 它那个data=s 会报错 data不能用.
多谢!!
- VB code
Public Function IncludeChinese(ByVal s As String) As Boolean '判断是否字符串中包含汉字 '定义字节数组指向字符串 Dim data() As Byte data = s '临时变量,Integer长度为2,正好用来判断是否是汉字,因为汉字是双字节的 Dim t As Integer '定义循环变量 Dim i As Integer '汉字边界值 '因为直接写&H9FA5会认为成integer的负数,所以要写成字符串,进行转换 Dim lb, ub As Long lb = CLng("&H4E00") '汉字最小值 ub = CLng("&H9FA5") '循环判断,汉字的范围是4E00 ~ 9FA5 '因为我不太懂vb6的技巧写法,就用一个比较繁琐的写法做类型转换 For i = 0 To UBound(data) Step 2 t = CLng("&h" + Hex(data(i) + data(i + 1) * 255)) '连续的2个字节拼接为一个integer If t >= lb And t <= ub Then IncludeChinese = True '找到任何一个汉字则返回True Exit Function End If Application.DoEvents() Sleep(1) Next IncludeChinese = False '不包含汉字 End Function
------解决方案--------------------
用正则处理啊
[\u4e00-\u9fa5]
------解决方案--------------------
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If IncludeChinese(TextBox1.Text) Then
MsgBox("有汉字", MsgBoxStyle.OkOnly)
Else
MsgBox("没有汉字", MsgBoxStyle.OkOnly)
End If
End Sub
Public Function IncludeChinese(ByVal s As String) As Boolean '判断是否字符串中包含汉字
Dim Sum&
Sum = 0
Dim char1 As Char
For c = 1 To Len(s)
char1 = Mid(s, c, 1)
If (AscW(char1) > -40870 And AscW(char1) < -19967) Or (AscW(char1) < 40870 And AscW(char1) > 19967) Then
Sum = Sum + 1
End If
Next c
If Sum Then
IncludeChinese = True
Else
IncludeChinese = False
End If
End Function
End Class
------解决方案--------------------
- C# code
string str = "a在"; Regex reg = new Regex(@"[\u4e00-\u9fa5]"); if (reg.IsMatch(str)) { MessageBox.Show("有汉字"); } else { MessageBox.Show("无汉字"); }
------解决方案--------------------
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim regX As New Regex("[\u4e00-\u9fa5]")
If regX.IsMatch(TextBox1.Text) Then
MsgBox("有汉字", MsgBoxStyle.OkOnly)
Else
MsgBox("没有汉字", MsgBoxStyle.OkOnly)
End If
End Sub
End Class