我想比较两个字符串和连字符,找出正确的断点
案例1:
dim Dictionarystr as string = "un-cen-tered"
dim Textstr as string = "uncen-tered"
结果:正确破裂。
案例2:
dim Dictionarystr as string = "un-cen-tered"
dim Textstr as string = "unce-ntered"
结果:错误的打破。</ p>
答案 0 :(得分:0)
首先,我会比较没有连字符的两个单词,以确保它们在正确的位置具有完全相同的字母。
然后我会计算每个连字符左侧的字母数(不计算连字符)。如果在Dictionarystr中也找到了Textstr中找到的所有数字,那么它就是匹配。
Ex:un-cenredred
un(在第一个连字符的左侧计算2个字母)
uncen(在第二个连字符的左侧计算5个字母)
案例1:
Dictionarystr:2,5 Textstr:5
* 5包含在上一个列表中,很好
案例2:
Dictionarystr:2,5 Textstr:4
* 4不在上一个列表中,不好
' This is your list of word with hyphen
Dim dictionaryWordsWithHyphen As New List(Of String)
' Pre-loaded information
Dim dictionaryWordsInfo As New Dictionary(Of String, List(Of Integer))
Sub Main()
' This is your list of word with hyphen
dictionaryWordsWithHyphen.Add("hou-se")
dictionaryWordsWithHyphen.Add("big-hou-se")
dictionaryWordsWithHyphen.Add("some-made-up-word")
' Pre-load the information in a way that is easy to search on
' This should be done once at the begining of the program
For Each word In dictionaryWordsWithHyphen
dictionaryWordsInfo.Add(GetFullWord(word), GetLetterCount(word))
Next
' Test on some words
Console.WriteLine(IsGoodWord("does-not-exists")) ' False
Console.WriteLine(IsGoodWord("big-hou-se")) ' True
Console.WriteLine(IsGoodWord("bighou-se")) ' True
Console.WriteLine(IsGoodWord("big-house")) ' True
Console.WriteLine(IsGoodWord("bigh-ouse")) ' False
Console.ReadLine()
End Sub
Function GetFullWord(ByVal word As String) As String
Return word.Replace("-", "")
End Function
Function GetLetterCount(ByVal word As String) As List(Of Integer)
Dim letterCount As New List(Of Integer)
Dim split() As String = word.Split("-")
Dim count As Integer = 0
For Each section As String In split
count += section.Length
letterCount.Add(count)
Next
Return letterCount
End Function
Function IsGoodWord(ByVal word As String) As Boolean
Dim fullWord As String = GetFullWord(word)
Dim letterCount As List(Of Integer) = GetLetterCount(word)
' Check if the word exists in the dictionary
If Not dictionaryWordsInfo.ContainsKey(fullWord) Then
Return False
End If
' Check if the letter count exists
For Each c As Integer In letterCount
If Not dictionaryWordsInfo(fullWord).Contains(c) Then
' The hyphen is at the wrong place
Return False
End If
Next
Return True
End Function