簡體   English   中英

如何比較兩個字符串的准確性

[英]How to compare two strings for accuracy

我正在制作這個無用的程序只是為了正確地重新編程,我正在努力比較兩個字符串的准確性。


我基本上有 2 個字符串:(示例)

(我比較的常數) 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

結束函數 兩個注釋部分是我來到這里之前嘗試的另一種方法。 代碼應該如下運行

比較字符串(“abcdefghijkl”,“abcdefghjkli”)

strNum 將達到 8。

百分比匹配 = ((8 / 12)*100)

*百分比匹配 = 75

返回 75

但是,它沒有返回這個,在線

If str1(x) = str2(x) Then

它返回一個錯誤,“索引超出了數組的范圍。” 我理解錯誤,只是不是我出錯的地方。

如果我可以提供更多信息,我會在看到通知后立即提供:)

提前致謝,

林斯萊普

如果你考慮字符串

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)

干杯!!!

您需要檢查給定字符串的長度,也不應超過界限,並且在檢查整個字符串之前也不要退出循環:

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

我知道這已經開放了一段時間,但我一直在研究這個。 您也必須尊重字符串的長度。 假設你有兩個字符串。 ABCDAEF AEF 是 ABCD 長度的 75%。 ABCD 中的每個字母的價值為 25%。 AEF 中有一個字母是正確的,那就是 A。 A = 25%: 75% * 25% = 0,75 * 0,25 = 0,1875 = 18,75% 字符串 AEF 是 18.75% 等於 ABCD。

希望你明白。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM