简体   繁体   English

比较两个字符串并找到字母位置匹配的位置

[英]Compare two strings and find where letter positions match

I want to do a bitwise and on two strings so that: 我想对两个字符串进行按位运算 ,以便:

Given: 鉴于:

 Dim word As String = "abcd"
 Dim temp As String = "a-d-"

I want to return only the 'a' 我只想返回'a'

Given: 鉴于:

 Dim word As String = "abcd"
 Dim temp As String = "a--d"

I want to return only the 'a--d' 我只想返回'a-d'

I have tried intersect, but it only finds characters in one string that match the characters in the other regardless of position. 我已经尝试过相交,但是无论位置如何,它只能在一个字符串中找到与另一个字符串匹配的字符。

I've used the '-' to represent spaces here. 我在这里用“-”表示空格。

Any suggestions would be appreciated. 任何建议,将不胜感激。

This will handle strings with mis-matched lengths: 这将处理长度不匹配的字符串:

Public Function CheckMask(ByVal word As String, ByVal mask As String) As String
    Dim wordChars() As Char = word.ToCharArray()
    Dim maskChars() As Char = mask.ToCharArray()

    Dim i As Integer = 0       
    While i < wordChars.Length AndAlso i < maskChars.Length
        If wordChars(i) <> maskChars(i) Then wordChars(i) = " "c
        i = i + 1
    End While

    'If string lengths are equal or the mask is longer, we're done
    'If the word is longer, need to set remaining characters to " "
    While i < wordChars.Length
        wordChars(i) = " "c
    End While

    Return New String(wordChars)
End Function
Dim Res As String = ""    
For i = 0 To Math.Min(StrA.Length, StrB.Length) - 1
    If StrA(i) = StrB(i) Then Res &= StrA(i) Else Res &= " "
Next
Return Res

This basically loops to the end of the shorter one of the two strings. 这基本上循环到两个字符串中较短的一个的末尾。 If the letters at a given position match the letter is added to the result, else a space is added. 如果给定位置的字母匹配,则将字母添加到结果中,否则添加空格。

    Dim sFirstWord As String = "qwerty"
    Dim sSecndWord As String = "qseftg"
    Dim sResult As String = ""

    For i As Integer = 0 To Math.Min(sFirstWord.Length, sSecndWord.Length) - 1
        If sFirstWord(i) = sSecndWord(i) Then
            sResult &= sFirstWord(i)
        Else
            sResult &= " "
        End If
    Next

sResult will hold: "qet " sResult将保存:“ qet”

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

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