vb 中获取某个字符的个数

2024-12-02 07:10:30
推荐回答(5个)
回答1:

VB6的代码:
Dim s As String
Dim Need as string '需要找的字符
Dim i as integer,Count as integer

s="abc.def.gh.i.gkl.mn"
Need = "."
Count = 0

For i=1 To Len(s)
if Mid(s,i,1)=Need then Count=Count+1
Next

Print Count

VB2005的代码:
Dim s As String = "abc.def.gh.i.gkl.mn"
Dim Need as string ="." '需要找的字符
Dim i ,Count as integer

For i=0 To s.length-1
if Mid(s,i,1)=Need then Count += 1
Next

Console.WriteLine(count)

(假设Option Strict为Off)

看了2楼的代码,思路很好的
不过Split函数要对多个字符串拆分赋值
还要用Preserve重新定义数组
在s过长时操作十分占用CPU
而如果字符串含有Unicode字符则不能用Byte数组处理
所以使用Mid函数(或.net的SubString函数)速度比较快

如果不限使用版本的话
VB2005中新增数据类型Char则是最好选择
Char类型的数组代替String操作起来快很多倍

回答2:

v

楼上的太过繁琐,而且要是数量巨大,很慢~~

Private Sub Command1_Click()
Dim s As String
s = "abc.def.gh.i.gkl.mn"
Text1 = Len(s) - Len(Replace(s, ".", ""))
End Sub

回答3:

dim n as Integer,s as string
s="abc.def.gh.i.gkl.mn"
n=0
for i=1 to len(s)
if mid(s,i,1)="." then n=n+1
next
print n

回答4:

Dim a As Variant
s = "abc.def.gh.i.gkl.mn"
a = Split(s, ".")
MsgBox UBound(a)

回答5:

?k