gpt4 book ai didi

vba - 查找并连接多次出现的字符

转载 作者:行者123 更新时间:2023-12-04 21:24:39 25 4
gpt4 key购买 nike

我只是在这里查看了可能的答案,但找不到。我的问题是我想找到在一个单词/短语中出现多次的字符。

例如:

如果我输入 Faseehh 结果应该是 e,h如果我输入 Fawwd 结果应该是 w如果我输入 Faroq 结果应该是 -
我开发了以下代码,但这给了我值(value)错误。

Function CountRept(textt As String)
Dim i As Integer
Dim temp As String
Dim aLetter As String

temp = StrConv(textt, vbUnicode)
temp = Left(temp, Len(temp) - 1)
aLetter = Split(temp, Chr(0))

For i = 1 To Len(textt)
If worksheetfunctions.CountIf(aLetter, Mid(textt, i, 1)) > 1 Then
textt = textt & "," & Mid(textt, i, 1)
End If
Next i
CountRept = textt & "," & Mid(textt, i, 1)
End Function

我的意图是将字符串分解为单个字符,然后使用 Mid() 进行比较并连接。非常感谢任何帮助和解释。谢谢

最佳答案

我不确定您是否只是在寻找相邻的字符。以下代码将在字符串中查找所有重复的字母,无论是否相邻。如果使用不区分大小写的搜索,示例字符串将返回“o”或“g,o”:

Function countRep(str as String)

'str = lcase(str) '--if you want case-insensitive search

Dim msg As String, curr As String
Dim i As Integer, k As Integer

'Make Array as large as the string
Dim letters() As String
ReDim letters(Len(str))

'Loop through letters of string
For i = 1 To Len(str)
curr = Mid(str, i, 1)
'Loop through the array for checks
For k = 1 To i
'Add letter to message if not already included
If letters(k) = curr And 0 = InStr(msg, curr) Then msg = msg & curr & ","
Next k
'Add letter to array for future checks
letters(i) = curr
Next i

'Remove trailing comma
countRep = Left(msg, Len(msg) - 1)

End Function

如果您只想要相邻的字符,您可以跳过使用数组,只需保存检查的最后一个字母,以便将其与以下字符进行比较。

关于vba - 查找并连接多次出现的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23881631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com