如何比较两个字符串的准确性

时间:2015-02-16 22:34:13

标签: vb.net string compare stringcomparer

我正在制作这个无用的程序只是为了正确地重新编程而且我在努力比较两个字符串的准确性。


我基本上有两个字符串:(示例)

(我相比较的常数)str1 =" abcdefghijkl"

(输入)str2 =" abcdefghjkli"

str2是正确的(包括)" h"。我想知道字符串的百分比是正确的。

这是我到目前为止的代码:

Private Function compareString(str1 As String, str2 As String)
'Compares str2 to str1 and returns a % match
Dim strNumber As Integer
Dim percentMatch As Integer
'Dim array1(16), array2(16) As Char
'array1 = str1.ToCharArray
'array2 = str2.ToCharArray

 For x = 0 To str1.Length
    'If array1(x) = array2(x) Then
    If str1(x) = str2(x) Then
        strNumber += 1
    Else
        Exit For
    End If
 Next
 percentMatch = ((strNumber / (str1.Length - 1)) * 100)
 percentMatch = CInt(CStr(percentMatch.Substring(0,4)))
 Return percentMatch

结束功能 这两个评论部分是我在来之前尝试的另一种方法。 代码运行如下

compareString(" abcdefghijkl"," abcdefghjkli")

strNum将获得8。

percentMatch =((8/12)* 100)

* percentMatch = 75

返回75

但是,它没有返回这个,在行

If str1(x) = str2(x) Then

它返回一个错误,"索引超出了数组的范围。"我理解错误,而不是我出错的地方。

如果我能提供更多信息,我会在看到通知后立即这样做:)

先谢谢,

Rinslep

3 个答案:

答案 0 :(得分:0)

如果你考虑字符串

str = "ABCDE";

str.Length是5.但如果使用基于0的索引对其进行索引,

str[0] = 'A'
...
str[4] = 'E'
'str[5] throws exception (5 = str.Length)

现在在你的

For x = 0 To str1.Length

如果你比较我的例子,当x等于字符串的长度时,你正在检查str [5],它超出了界限,因此抛出了异常。

将该行更改为

Dim shorterLength = IIf(str1.Length < str2.Length, str1.Length, str2.Length); 'So that you cannot go beyond the boundary
For x = 0 To (shorterLength - 1)

干杯!!!

答案 1 :(得分:0)

你需要检查给定字符串的长度,也不要超过界限,也不要在检查整个字符串之前退出循环:

Dim x As Integer = 0  
While x < str1.Length AndAlso x < str2.Length
    If str1(x) = str2(x) Then
        strNumber += 1
    End If
    i = i + 1
End While

答案 2 :(得分:0)

我知道这已经有一段时间了,但我一直在研究这个问题。你也必须尊重字符串的长度。假设你有两个字符串。 ABCDAEF。 AEF是ABCD长度的75%。 ABCD中的每个字母值25%。并且有一个字母在AEF中是正确的,而且是A.而A = 25%:75% * 25% = 0,75 * 0,25 = 0,1875 = 18,75%。字符串AEF等于ABCD的18,75%。

希望你理解。 :)