我想我有一个简单的任务
我的代码生成 2 个字符串
字符串 A(由换行符分隔)
1
2
3
4
字符串 B(由换行符分隔)
5
6
7
8
我试图弄清楚如何将这些单独的字符串组合成一个,就好像它们是彼此相邻的两列,用逗号分隔
结果将是字符串 C
1,5
2,6
3,7
4,8
谢谢!
我想我有一个简单的任务
我的代码生成 2 个字符串
字符串 A(由换行符分隔)
1
2
3
4
字符串 B(由换行符分隔)
5
6
7
8
我试图弄清楚如何将这些单独的字符串组合成一个,就好像它们是彼此相邻的两列,用逗号分隔
结果将是字符串 C
1,5
2,6
3,7
4,8
谢谢!
我会使用美妙的 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 很有趣?
怎么样?
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)
将两个字符串都转换为 char[] (Char() - 字符数组) (string.ToCharArray())。
遍历数组。
您将需要检查边界条件(例如,如果字符串长度不同怎么办)。
'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