Home > Back-end >  Split by space vb.net
Split by space vb.net

Time:09-24

How to split to 2 different string by space split?

I have a string with name and link.
I need to split it to 2 different strings.

[LVL 8] Logan_Aasd http://www.google.com/1  
[LVL 8] Jack_Jackosn http://www.google.com/2  
[LVL 8] Mask_Off http://www.google.com/3  
[LVL 8] Dream_Alive http://www.google.com/4  

And I need to split them this way to a different richtextbox:

[LVL 8] Logan_Aasd   
[LVL 8] Jack_Jackosn   
[LVL 8] Mask_Off   
[LVL 8] Dream_Alive  
http://www.google.com/1   
http://www.google.com/2   
http://www.google.com/3   
http://www.google.com/4  

I've tried to split it by the spaces and then use For Each. The code isn't right but I think it's close to what I need.

Dim text As String = RichTextBox2.Text
Dim x() As String
x = text.Split(" "c)
For Each s As String In x
    RichTextBox3.Text = s
Next

CodePudding user response:

You can use something like this:

Dim modifiedLines = New List(Of String)()
For index As Integer = 0 To lines.Length - 1
    Dim url = lines(index).Substring(lines(index).LastIndexOf(" "c)   1)
    modifiedLines.Insert(index, lines(index).Replace(url, String.Empty))
    modifiedLines.Add(url)
Next

This assumes that you've split up your content into a String array named lines.

Basically what this does is:

  1. Create a List to store the new lines
  2. Loop over each existing line
  3. Get the URL by splitting on the last instance of a space on the currently iterated line, then getting the substring from that space to the end
  4. Insert the existing line, replacing the URL with an empty String at the current index
  5. Add the URL to the end of the collection

There is a bit of concern in that if your URL appears twice in the string then it would be removed when it goes to call the Insert command, but based on your example I don't think that is likely to happen.

Live Example: https://dotnetfiddle.net/ejlj9y

  • Related