循环通过2个字符串并结合VB 2010

时间:2013-09-27 02:12:42

标签: vb.net

我认为我有一个简单的任务

我的代码生成2个字符串

字符串A(由换行符分隔)

1
2
3
4

字符串B(由换行符分隔)

5
6
7
8

我想弄清楚如何将这些单独的字符串组合成一个,好像它们是彼此相邻的两列,用逗号分隔

结果将是字符串C

1,5
2,6
3,7
4,8

谢谢!

4 个答案:

答案 0 :(得分:0)

将两个字符串转换为char [](Char() - 字符数组)(string.ToCharArray())。

通过数组迭代。

您需要检查边界条件(例如,如果字符串的长度不同,该怎么办)。

答案 1 :(得分:0)

'first string
Dim a As String = "abcd"
'second string
Dim b As String = "defghijk"

'Remove Line feeds
Dim tempA As String = a.Replace(vbLf, "")
Dim tempB As String = a.Replace(vbLf, "")
'Get the string with the larger size.
Dim largerSize As Integer = If(tempA.Length > tempB.Length, tempA.Length, tempB.Length)
'We use a string builder to build our new string
Dim sb As New StringBuilder()
'Loop on the larger size and only insert if inside range of string
For i As Integer = 0 To largerSize - 1
    If i < tempA.Length Then
        sb.Append(a(i))
        sb.Append(",")
    End If
    If i < tempB.Length Then
        sb.Append(b(i))
    End If

    sb.Append(vbLf)
Next
'this is the result
Dim combined As String = sb.ToString()

修改答案以删除换行

编辑字符串结果后的另一个编辑

使其成为VB.NET的另一个编辑

答案 2 :(得分:0)

怎么样?

    Dim A As String = "1" & vbCrLf & "2" & vbCrLf & "3" & vbCrLf & "4"
    Dim B As String = "5" & vbCrLf & "6" & vbCrLf & "7" & vbCrLf & "8"
    Debug.Print(A)
    Debug.Print(B)

    Dim tmp As New List(Of String)
    tmp.AddRange(A.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries))
    Dim values() As String = B.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
    For i As Integer = 0 To values.Length - 1
        If i <= tmp.Count - 1 Then
            tmp(i) = tmp(i) & "," & values(i)
        Else
            tmp.Add("," & values(i))
        End If
    Next

    Dim C As String = String.Join(vbCrLf, tmp.ToArray)
    Debug.Print(C)

答案 3 :(得分:0)

我会使用精彩的Linq Zip! (我首先String.Split带有换行符的2个字符串)然后

Dim column1() As String = {"1", "2", "3", "4"}
Dim column2() As String = {"5", "6", "7", "8"}
Dim mixed= column1.Zip(column2, Function(first, second) first & "," & second)

编辑:

哦,然后,如果你想把它重新变成1个字符串,你可以使用String.Join但Linq也很有趣!所以你可以写:

Dim mixed= column1.Zip(column2, Function(first, second) first & "," & second)
                  .Select(i => i.Boo)
                  .Aggregate((i, j) => i + vbLf + j)

我是否提到Linq很有趣?