Simple get initials from string - Visual Basic - vb.net

Simple beginner exercise:
There's an input box where you put in your name seperated by spaces, then get the first letter from the first and last name and out put it to a label
I.e (Joe Bob) = JB
I know this could be done with an array, but the exercise is more to using string functions like substring, IndexOf, Remove, Replace etc...

There is the handy string method Split which splits a string at whitespaces by default, if you don't specify another delimiter.
Dim words As String() = TextBox1.Text.Split()
Dim initials As String = ""
For Each word As String In words
initials &= word(0)
Next
Note: Strings can be indexed as if they were Char arrays. word(0) is the first character of word.
initials &= word(0)
is shorthand for
initials = initials & word(0)

You can try this:
dim str as String=TextBox1.Text
Label1.Text=str.Remove(1, str.LastIndexOf(" ")).Remove(2)
If you want, you can do it in one line:
Label1.Text = TextBox1.Text.Remove(1, TextBox1.Text.LastIndexOf(" ")).Remove(2)

Could try something like this too!
Dim str As String = textBox1.Text
Dim initials As String = New String(str.Split(" "c).Select(Function(f) f(0)).ToArray)

You can try using the SubString and Split Methods.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim myInitials As String
Dim myName As String = "Joe Bob"
myInitials = myName.Substring(0, 1) & myName.Split(" ")(1).Substring(0, 1)
End Sub

Related

VB.net Trying to get text between first and second slashs only

I am trying to retrive the value of the text between the first and second backslashes... but my coding skills have brought me this far and no futher.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim TEST As String = "ONE\TWO\TRHREE\FOR\FIVE"
Dim splitted = TEST.Split("\"c)
Dim values = splitted.Skip(1).Take(splitted.Length - 2).ToArray()
MsgBox(values)
End Sub
Use regular expressions
Dim TEST as String = "ONE\TWO\TRHREE\FOR\FIVE"
Dim matches As MatchCollection = Regex.Matches(TEST, "\\(.|\n)*?\\", RegexOptions.IgnoreCase)
Now if you want those values to come out in message boxes
For Each ma As Match In matches
MsgBox(ma.ToString.Trim({"\"c}))
Next
This will get you both "TWO" and "FOR". If you want just "TWO" then matches(0) is all you need.
Alternatively, if you just want to get the matches into an array in one line, then have each value of the array in a single message box:
Dim values = Regex.Matches(TEST, "\\(.|\n)*?\\").Cast(Of Match)().[Select](Function(m) m.Value).ToArray()
MsgBox(String.Join(", ", values))
Use the Split function. It will split on a string and store the separated values in an array. This is the easiest of all the answers here and is probably the most correct way of doing this.
This is the VB way of doing it:
Dim s() As String = Split("ONE\TWO\TRHREE\FOR\FIVE", "\")
MessageBox.Show(s(1))
And this is the .NET way of doing it:
Dim mainString As String = "ONE\TWO\TRHREE\FOR\FIVE"
Dim s() As String = mainString.Split("\")
MessageBox.Show(s(1))
If you want "Two" as result, this should be the simplest approach:
Dim allToken As String() = "ONE\TWO\TRHREE\FOR\FIVE".Split("\"c)
Dim relevantPart = allToken.Skip(1).Take(1)
Dim result As String = String.Concat(relevantPart) ' "Two"
If you don't want a single string but a String() use ToArray:
Dim result As String() = relevantPart.ToArray()
Side-Note: you can't output an array directly, you could use String.Join:
MsgBox(String.Join(", ", result)) ' f.e. comma separated

How to find indexes for certain character in a string VB.NET

I'm beginner with VB.net.
How do I read indexes for certain character in a string? I read an barcode and I get string like this one:
3XXX123456-C-AA123456TY-667
From that code I should read indexes for character "-" so I can cut the string in parts later in the code.
For example code above:
3456-C
6TY-667
The length of the string can change (+/- 3 characters). Also the places and count of the hyphens may vary.
So, I'm looking for code which gives me count and position of the hyphens.
Thanks in advance!
Use the String.Splt method.
'a test string
Dim BCstring As String = "3XXX123456-C-AA123456TY-667"
'split the string, removing the hyphens
Dim BCflds() As String = BCstring.Split({"-"c}, StringSplitOptions.None)
'number of hyphens in the string
Dim hyphCT As Integer = BCflds.Length - 1
'look in the debuggers immediate window
Debug.WriteLine(BCstring)
'show each field
For Each s As String In BCflds
Debug.WriteLine(String.Format("{0,5} {1}", s.Length, s))
Next
'or
Debug.WriteLine(BCstring)
For idx As Integer = 0 To hyphCT
Debug.WriteLine(String.Format("{0,5} {1}", BCflds(idx).Length, BCflds(idx)))
Next
If all you need are the parts between hyphens then as suggested by dbasnett use the split method for strings. If by chance you need to know the index positions of the hyphens you can use the first example using Lambda to get the positions which in turn the count give you how many hyphens were located in the string.
When first starting out with .NET it's a good idea to explore the various classes for strings and numerics as there are so many things that some might not expect to find that makes coding easier.
Dim barCode As String = "3XXX123456-C-AA123456TY-667"
Dim items = barCode _
.Select(Function(c, i) New With {.Character = c, .Index = i}) _
.Where(Function(item) item.Character = "-"c) _
.ToList
Dim hyphenCount As Integer = items.Count
Console.WriteLine("hyphen count is {0}", hyphenCount)
Console.WriteLine("Indices")
For Each item In items
Console.WriteLine(" {0}", item.Index)
Next
Console.WriteLine()
Console.WriteLine("Using split")
Dim barCodeParts As String() = barCode.Split("-"c)
For Each code As String In barCodeParts
Console.WriteLine(code)
Next
Here is an example that'll split your string and allow you to parse through the values.
Private Sub TestSplits2Button_Click(sender As Object, e As EventArgs) Handles TestSplits2Button.Click
Try
Dim testString As String = "3XXX123456-C-AA123456TY-667"
Dim vals() As String = testString.Split(Convert.ToChar("-"))
Dim numberOfValues As Integer = vals.GetUpperBound(0)
For Each testVal As String In vals
Debug.Print(testVal)
Next
Catch ex As Exception
MessageBox.Show(String.Concat("An error occurred: ", ex.Message))
End Try
End Sub

How to filter anything but numbers from a string

I want to filter out other characters from a string as well as split the remaining numbers with periods.
This is my string: major.number=9minor.number=10revision.number=0build.number=804
and this is the expected output: 9.10.0.804
Any suggestions?
As to my comment, if your text is going to be constant you can use String.Split to remove the text and String.Join to add your deliminators. Quick example using your string.
Sub Main()
Dim value As String = "major.number=9minor.number=10revision.number=0build.number=804"
Dim seperator() As String = {"major.number=", "minor.number=", "revision.number=", "build.number="}
Console.WriteLine(String.Join(".", value.Split(seperator, StringSplitOptions.RemoveEmptyEntries)))
Console.ReadLine()
End Sub
If your string does not always follow a specific pattern, you could use Regex.Replace:
Sub Main()
Dim value as String = "major.number=9minor.number=10revision.number=0build.number=804"
Dim version as String = Regex.Replace(value, "\D*(\d+)\D*", "$1.") ' Run the regex
version = version.Substring(0, version.Length - 1) ' Trim the last dot
End
Note you should Imports System.Text.RegularExpressions.

VB 2010 - Replace all letters of a string with a dash

VB 2010 - Beginner here,
I am creating a hangman game for a assignment and I am having trouble replacing the text of a string with dashes. I am not sure if I need to convert the string to a charArray() or if I can use the string.Replace function. i know i need to loop it unsure how..
terribly confused i need some help. As I am learning please try and keep it simple with reason please.
My sandbox code so far:
Imports System.IO
Public Class Form1
Private Const TEST = "test.txt"
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim WordString As String = Nothing
Dim NewWordInteger As Integer
Dim RandomWord As New Random(System.DateTime.Now.Millisecond) 'Load a new word at the time it was initiated
'Load words from test file into the array
Dim WordArray() As String = File.ReadAllLines(TEST) 'Reads words from list and declares each as a string
'Select Random word from the number of words in the dictionary.txt file
NewWordInteger = RandomWord.Next(0, 4)
'Display RandomWord in textbox as STRING..
WordString = WordArray(NewWordInteger) ' Assigns wordstring a word from the arrany & random by the NewWordInterger Substring..
WordDisplayTextBox.Text = WordString ' will display the word in the textbox
SolveLabel.Text = WordString ' will display the word in the Solve label
'Will shoe the array word and the word/string position in the TEST.file
ListBox1.Items.Add(WordString) ' will show the word
ListBox2.Items.Add(NewWordInteger) ' will show the string position in the TEST.file
'search string and replace letters with _ (Dashes)
Dim charArray() As Char = WordDisplayTextBox.Text.ToCharArray
For Each item As Char In WordDisplayTextBox.Text
WordDisplayTextBox.Text = WordString.Replace(item, "_")
Next
End Sub
End Class
If you want to replace all the characters of a string with dashes, why not just make a new string that consists only of dashes, that is the same length as the starting string? Isn't that the same thing?
WordDisplayTextBox.Text = New String("_", WordString.Length)
Loop through the length of the WordString and each time write "__" inside the WordDisplayTextBox
For i As Integer = 1 To Len(txtWordString.Text)
WordDisplayTextBox.Text += "__" + " " 'Space separates the dashes for clarity
Next

Splitting a string on comma and printing the results

I am using the following code to split a string and retrieve them:
Private Sub Button1_Click(sender As Object, e As EventArgs)
Handles Button1.Click
Dim s As String = "a,bc,def,ghij,klmno"
Dim parts As String() = s.Split(New Char() {","c})
Dim part As String
For Each part In parts
MsgBox(part(0))
Next
End Sub
But the message box shows only the first character in each splitted string (a,b,d,g,k).
I want to show only the first word, what am I doing wrong?
It is not clear from your question, but if you want only the first word in your array of strings then no need to loop over it
Dim firstWord = parts(0)
Console.WriteLine(firstWord) ' Should print `a` from your text sample
' or simply
Console.WriteLine(parts(0))
' and the second word is
Console.WriteLine(parts(1)) ' prints `bc`
You already have each part - just display it:
For Each part In parts
MsgBox(part)
Next
part(0) will return the first item in the character collection that is a string.
If you want a specific index into the returned string array (as suggested by your comment), just access it directly:
Dim parts As String() = s.Split(New Char() {","c})
Dim firstPart As String = parts(0)
Dim thirdPart As String = parts(2)
You need to show part not part(0)
For Each part In parts
MsgBox(part)
Next