简体   繁体   English

一个字符串在VBA中包含一个字符的次数

[英]how many times a string contains a char in VBA

is ther any way to know how many times a string contains a specific char? 有什么办法知道一个字符串包含一个特定字符多少次?

eg how many times does the string "strin" contains a comma. 例如,字符串“ strin”包含几次逗号。

    Dim strin as strin
    strin = "qwe, asd, zcx"

An old "trick" is to replace the string with something else, and check the difference in lengths of the string before and after doing the replace. 一个古老的“技巧”是用其他东西替换字符串,并在进行替换之前和之后检查字符串长度的差异。

Dim replaced as string
replaced = Replace(strin, ",", "")
' count = Len(string) - Len(replaced)

If you had to count a multi-character string, like a comma and a space, you would have to divide the results by the length of the string you were replacing: 如果必须计算一个多字符字符串,例如逗号和空格,则必须将结果除以要替换的字符串的长度:

Dim replaced as string
replaced = Replace(strin, ", ", "")
' count = (Len(string) - Len(replaced)) / 2

I think the best approach is to use a function. 我认为最好的方法是使用函数。

The code below should do the trick. 下面的代码应该可以解决问题。

sub TestCharCountFunction ' this sub is for testing the function

strin = "qwe, asd, zcx"

   msgbox  "Character appears " & charcounter( strin, "," ) & " time(s)"

end sub

function CharCounter (byval MyString as string, byval CharToSearch as string) as integer


dim X as integer

charcounter = 0

for X= 1 to len(mystring)

    if mid(mystring, x,1) = chartosearch then charcounter = charcounter + 1

next

end function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM