连续两个字符串

时间:2015-05-11 11:05:32

标签: vb.net string concatenation

我想合并两个字符串

示例:

第一个字符串: www.org.a.org

第二个字符串: .org.lb

结果字符串: www.org.a.org.lb

示例:

第一个字符串: www.google.com

第二个字符串: google.com

结果字符串: www.google.com

dim s1 as String = "www.org.a.org"
dim s2 as String = ".org.lb"
dim s2 as String = s1 & s2 ' www.org.a.org.org.lb !!

2 个答案:

答案 0 :(得分:0)

严格遵循您提供的示例,我会创建一个Function,将字符串合并在一起。

Function应检查string1是否包含string2以了解是否需要合并。如果此检查为false,则将string2拆开并检查每个部分是否在string1中,如果不是,则将其添加到结尾(假设在合并时总是添加到结尾)。

Imports System

Public Module Module1

    Public Sub Main()
        Console.WriteLine(MergeString("www.org.a.org", ".org.lb"))
        Console.WriteLine(MergeString("www.google.com", "google.com"))
    End Sub

    Public Function MergeString(ByVal str1 As String, ByVal str2 As String) As String
        If str1.EndsWith(str2)
            Return str1
        Else
            Dim str2Pieces() = str2.Split("."c)
            For i = 0 to str2Pieces.Length - 1
                If String.IsNullOrEmpty(str2Pieces(i)) = False
                    If str1.EndsWith(str2Pieces(i)) = False
                        str1 = str1 & "." & str2Pieces(i)
                    End If
                End If
            Next

            Return str1
        End If
    End Function
End Module

输出:

  

www.org.a.org.lb

     

www.google.com

答案 1 :(得分:0)

看看你的问题,似乎你可能有一些你没有陈述的规则。以下函数确实按照您的要求执行,并在您给出的两个示例中返回您期望的字符串。

Function MergeStrings(str1 As String, str2 As String) As String
    Dim pos, overlap As Integer
    If str1.Length > str2.Length Then pos = str1.Length - str2.Length 

    overlap = str1.Length - pos
    Do While overlap > 0
        If str1.Substring(pos, overlap) = str2.Substring(0, overlap) Then Return str1.Substring(0, pos) & str2 
        pos += 1
        overlap = str1.Length - pos
    Loop
    Return str1 & str2 
End Function