Split string by " " in VB.NET - vb.net

Let’s say that this is my string:
1 2 3
I want to split the string by " " (space) and display every time part of my string.

This will do what you need:
Dim str As String = "1 2 3"
Dim strarr() As String
strarr = str.Split(" "c)
For Each s As String In strarr
MessageBox.Show(s)
Next

Related

Remove description from list in RichTextBox

I have a list of accounts in a RichTextBox:
username:password|description
username1:password1|description
username3:password3|description3
username4:password5|description6
username1:password3|description5
username2:password4|description5
username2:password3|description3
The amount of rows in the list is arbitrary.
I want to remove the "|description" part of each row. Any suggestions?
Use a Regex
Dim rx As New System.Text.RegularExpressions.Regex("\|(.+)")
RichTextBox1.Text = rx.Replace(RichTextBox1.Text, "")
This will remove any number of characters beginning with and including the pipe |. It will work with a RichTextBox having a Text property of any length (any number of rows).
If you want to leave just the password, you can do two replaces
Dim rx As New System.Text.RegularExpressions.Regex("\|(.+)")
RichTextBox1.Text = rx.Replace(RichTextBox1.Text, "")
rx = New Regex("(.+):")
RichTextBox1.Text = rx.Replace(RichTextBox1.Text, "")
Just remove anything up to and including the :
And just in case you ask, you could also remove the password with this
Dim rx As New System.Text.RegularExpressions.Regex(":(.+)\|")
RichTextBox1.Text = rx.Replace(RichTextBox1.Text, "|") ' or replace with ":"
Without regex?
Dim lines = RichTextBox1.Text.Split(vbLf)
Dim elements = lines.Select(Function(line) line.Split({":"c, "|"c}))
' password
RichTextBox1.Text = String.Join(vbLf, elements.Select(Function(element) element(1)))
' username:password
RichTextBox1.Text = String.Join(vbLf, elements.Select(Function(element) element(0) & ":" & element(1)))
' you get the idea
Spilt the text into an array then rewrite the items in the array to the text box
Dim arr1() As String=Split (rtb.Text,VbLf)
Dim finalstring As String= ""
For x As Integer=0 to Ubound(arr1) - 1
Dim arr2 () As String = Split (arr1 (x), "|")
finalstring += arr2 (0) & vbNewLine
Next
rtb.Text= finalstring
to show just the password; use the same technique as above
Dim arr1() As String=Split(rtb.Text,VbLf)
Dim finalstring As String= ""
For x As Integer = 0 to Ubound(arr1) - 1
Dim arr2 () As String = Split (arr1 (x), "|")
For x As Integer=0 to Ubound(arr2) - 1
Dim arr3 () As String = Split (arr2 (0), ":")
finalstring += arr3 (1) & vbNewLine
Next
Next
rtb.Text= finalstring

Insert a string at specified indexof position using VB.NET

I'm trying to insert the string " " or a blank space in a specified index on a textbox like so:
textbox = heybrowhatsup
I want to insert an " " on the indexes 4, 8 and 14, to get "hey bro whats up", but my code just won't work.
My code:
Dim str As String = sum2.Text
Dim insStr As String = " "
Dim strRes As String = str.Insert(15, insStr)
Dim str As String = sum2.Text
Dim insStr As String = " "
Dim strRes As String = str.Insert(3, insStr)
strRes = strRes.Insert(7, insStr)
strRes = strRes.Insert(12, insStr)
You must use strRes.Insert for second or more.
Any string manipulation creates a new String object. What you're doing is working perfectly in that it is creating a new String with the specified substring inserted at the specified position. As is always the case, if you want that String displayed in your TextBox then you must assign that String to the Text property of that TextBox.
The Space function is useful for formatting output and clearing data in fixed-length strings.
You can use space function as below.
Dim str As String = "heybrowhatsup"
Dim strRes As String = str.Insert(3, Space(1)).Insert(7, Space(1)).Insert(13, Space(1))
Or
You can do the same with insert function.
Dim str As String = "heybrowhatsup"
Dim insStr As String = " "
Dim strRes As String = str.Insert(3, insStr).Insert(7, insStr).Insert(13, insStr)

Splitting a full name string to separate variables (first, middle and last) without using the split function

So I was given the task to bifurcate a string with a full name and then print out the first and last name separately. For instance, input: Steve Robertson, output: First name: Steve Last name: Robertson.
I succeeded, it was fairly easy. But I'm having having trouble in dividing a full name string to first, last and middle. Here's what I've done so far.
Sub Main()
Dim string1 As String = ""
Dim string2 As String = ""
Dim string3 As String = ""
Dim string4 As String = ""
Dim temp1 As String = ""
Dim integer1 As Integer = 1
Console.WriteLine("Enter the string you want to bifurcate: ")
string1 = Console.ReadLine()
While integer1 <> 0
integer1 = InStr(string1, " ")
Console.WriteLine(string1)
string2 = Left(string1, integer1)
Console.WriteLine(string2)
string3 = Mid(string1, integer1 + 1)
Console.WriteLine(string3)
string4 = Mid(string1, integer1 + 1)
Console.WriteLine(string4)
string1 = string4
End While
Console.WriteLine("First name is: " & string2)
Console.WriteLine("Second name is: " & string3)
Console.WriteLine("Third name is: " & string4)
Console.ReadKey()
End Sub
Keep in mind that I'm only printing almost every single variable to see what their value is during the iteration. I can only use the len() function and whatever is already in the code.
EDIT:
So I fiddled around and finally got the thing, without the loop, but I was wondering if there was a cleaner/right way to do this without repeating the variables and also not needing to create any new ones either.
Sub Main()
Dim string1 As String = ""
Dim string2 As String = ""
Dim string3 As String = ""
Dim string4 As String = ""
Dim integer1 As Integer
Console.WriteLine("Enter the string you want to split: ")
string1 = Console.ReadLine()
integer1 = InStr(string1, " ")
string2 = Left(string1, integer1)
string3 = Mid(string1, integer1 + 1)
integer1 = InStr(string3, " ")
string4 = Left(string3, integer1)
string3 = Mid(string3, integer1 + 1)
Console.WriteLine("The first name is: " & string2)
Console.WriteLine("The middle name is: " & string4)
Console.WriteLine("The last name is: " & string3)
Console.ReadKey()
End Sub
Here is one way to do it. Loop through the characters from the input of the user. Continue to do so concatenating them together and throw them into a List(Of String) that way the can be easily written out at the end... This account's for multiple spaces as well if there's more than one in between names. Also I put some comment's into the code so it can be easier to understand.
Note: This is only one way to do it... (there are other ways)
CODE TRIED AND TESTED
Dim nList As New List(Of String)
Dim uStr As String = String.Empty
Console.WriteLine("Enter the string you want to bifurcate: ")
uStr = Console.ReadLine()
If Not String.IsNullOrEmpty(uStr) Then 'Make sure something was entered...
Dim tStr As String = String.Empty
'Loop through user's input...
Do Until uStr = String.Empty
For Each c As Char In uStr
If Not Char.IsWhiteSpace(c) Then 'If it's a space we can add to the current string...
tStr &= c.ToString
Else
'We can assume its another section of the name...
Exit For
End If
Next
'If its a space, remove it from current string...
If String.IsNullOrEmpty(tStr) Then uStr = uStr.Remove(0, tStr.Length + 1) : Continue Do
'Add the string to the list, could be first name, middle or lastname?
If nList.Count = 0 Then
nList.Add("First Name: " & tStr)
ElseIf nList.Count = 1 Then
nList.Add("Middle Name: " & tStr)
ElseIf nList.Count = 2 Then
nList.Add("Last Name: " & tStr)
End If
'Now we can remove what we got from the users input...
uStr = uStr.Remove(0, tStr.Length)
tStr = String.Empty
Loop
End If
'Finally write out the values...
Console.WriteLine(String.Join(Environment.NewLine, nList.ToArray))
Console.ReadLine()
Screenshot Of Program
Maybe something like this
Dim fullName = "Juan Perez"
Dim name = fullName.Substring(0, fullName.IndexOf(" "))
Dim lastName = fullName.Substring(fullName.IndexOf(" ") + 1)
How to separate full name string
I would suggest that you design extension methods that will return First and Last Name
Module Module1
<Extension()>
Public Function returnFirst(ByVal fullName As String) As String
Return fullName.Substring(0, fullName.IndexOf(" "))
End Function
<Extension()>
Public Function returnLast(ByVal fullName As String) As String
Return fullName.Substring(fullName.IndexOf(" ") + 1)
End Function
End Module
'call it
'import module1
Dim Name as string = 'FirstName LastName'
MessageBox.Show(NAME.returnFirst)
MessageBox.Show(NAME.returnLast)

How to Split a string using VB Macro

I need to split this number 309701406 as 30 970 140 6. How can I do with VB macro script. Any one please look into this and assist.
AS mentioned in a comment to your Question, you can use the following:
SomeString = Mid(StringName, Start, Length)
Putting that into a Sub will look as follows:
Option Explicit
Sub SplitStringSub()
Dim OriginalString As String
Dim String1 As String
Dim String2 As String
Dim String3 As String
Dim String4 As String
OriginalString = 309701406
'Mid wants a String input
'Because of the need to split the Numerical String it is not explicity required to have the " " around then String input line.
'Should you want to Split a String of Alphabetical Characters the " " will definitely be required.
String1 = Mid(OriginalString, 1, 2)
String2 = Mid(OriginalString, 3, 3)
String3 = Mid(OriginalString, 6, 3)
String4 = Mid(OriginalString, 9, 1)
End Sub
If the 0 is delimiter you can do this.
Dim str As String
Dim aTmp() As String
str = "309701406"
aTmp() = Split(str, "0")
str = Join(aTmp, "0 ")
aTmp() = Split(str, " ")

loop through 2 strings and combine VB 2010

i have a simple task i think
my code generates 2 strings
string A (separated by line feeds)
1
2
3
4
String B (separated by line feeds)
5
6
7
8
i am trying to figure out how to combine these separate strings into one as if they were two columns next to each other, separated by a comma
the result would be string C
1,5
2,6
3,7
4,8
Thanks!
How about something like?
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)
Convert both strings to char[] (Char() - character array) (string.ToCharArray()).
Iterate thru the arrays.
You will need to check boundary conditions (e.g. what if the strings are different lengths).
'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()
Edit answer to remove line feeds
Another Edit after string result edited
Another edit to make it VB.NET
I would use the wonderful Linq Zip! (I would first String.Split the 2 strings with the line-feed character) and then
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)
edit:
oh, and then, if you want to have it back into 1 string, you can either use String.Join but Linq is fun too! So you can write :
Dim mixed= column1.Zip(column2, Function(first, second) first & "," & second)
.Select(i => i.Boo)
.Aggregate((i, j) => i + vbLf + j)
Did I mention that Linq is fun?