Re: Combining two strings
Quote:
Originally Posted by
harryjjacobs
Hi there,
I have two multi-line strings which I would like to be able to read line by line and then combine so that they alternate. Like this:
My two strings:
String 1:
String 2:
And I would like them to be combined in to one string that looks like this:
Geoff
Chris
Bob
Tom
Jim
Steve
And then each line placed in to a listbox...
I can't really figure out which order you are using. Also are there always an equal amount of strings (presumeably seperated by a new line) in each string?
#EDIT: If I'm right in assuming, that you made a typo, and that the names are to be in alternating order, you can try the following (also assuming that the strings are seperated by a single newline):
vb.net Code:
Private Function join_strings(ByVal names_a As String, ByVal names_b As String) As String
Dim n_a() As String = names_a.Replace(Environment.NewLine, ";").Split(";")
Dim n_b() As String = names_b.Replace(Environment.NewLine, ";").Split(";")
If n_a.Count = n_b.Count Then
Return String.Join(Environment.NewLine, Enumerable.Range(0, n_a.Count).Select( _
Function(i) n_a(i) & Environment.NewLine & n_b(i)))
End If
Return String.Empty
End Function
and use the function as follows:
vb.net Code:
'Question 1: Joining the 2 strings into a single string with alternating names:
Dim alt_names As String = join_strings(string1, string2)
MessageBox.Show(alt_names)
'Question 2: Filling them into a listbox.
ListBox1.Items.AddRange(alt_names.Replace(Environment.NewLine, ";").Split(";"))
Regards Tom