How can I seperate the values in the textbox to show in different labels using button? - vb.net

i want to be able to separate the values in a textbox and display the separated values in different labels using a button
this is what i want to happen:
input "Ac2O3" on textbox
Be able to separate "Ac", "2", "O", and "3".
Show the separated values in different textboxes using a button
im using visual basic 2012
im sorry im still new to this
thanks in advance!!

You can access different character of the string with the index.
Dim input As String = "Ac2O3"
Dim part1 As String = input(0) & input(1)
Dim part2 As String = input(2)
Dim part3 As String = input(3)
Dim part4 As String = input(4)
If you don't know how to handle the button event or how to display text in a textbox, that would be different questions.

This code creates a structure called Element to make the results from the function clearer - add this to your main class that the function is going to be placed in. The main function takes a string as it's input and produced a list of structures of Element as it's output. There probably are shorter ways to do this, but I'm a fairly basic programmer who likes a puzzle - hope this helps - Dont forget to accept the answer by clicking on the tick. If you have any queries please dont hesitate to ask
Structure Element
Dim symbol As String
Dim elementCount As Int16
End Structure
Function ParseFormula(ByVal compoundString As String) As List(Of Element)
Dim tempParseFormula = New List(Of Element)
Dim firstLetter As String = "[A-Z]"
Dim secondLetter As String = "[a-z]"
Dim number As String = "[0-9]"
Dim tempElementCount As String = ""
Dim maxIndex As String = compoundString.Length - 1
Dim i As Integer = 0
Dim parsedElement As New Element
While i <= maxIndex
Dim tempChar As String = compoundString(i)
Select Case True
Case tempChar Like firstLetter
parsedElement.symbol = parsedElement.symbol & tempChar
Case tempChar Like secondLetter
parsedElement.symbol = parsedElement.symbol & tempChar
Case tempChar Like number
tempElementCount = tempElementCount & tempChar
End Select
If i = maxIndex Then
If Val(tempElementCount) = 0 Then
tempElementCount = 1
End If
parsedElement.elementCount = Val(tempElementCount)
tempParseFormula.Add(parsedElement)
parsedElement.symbol = ""
parsedElement.elementCount = 0
tempElementCount = ""
Exit While
End If
i += 1
If compoundString(i) Like firstLetter Then
If Val(tempElementCount) = 0 Then
tempElementCount = 1
End If
parsedElement.elementCount = Val(tempElementCount)
tempParseFormula.Add(parsedElement)
parsedElement.symbol = ""
parsedElement.elementCount = 0
tempElementCount = ""
End If
End While
Return tempParseFormula
End Function

Related

Retrieve everything after a split in string VB.net

I'm needing to return the value of a string after it's been split in VB.Net.
The string will be something along the lines of:
someexpression1 OR someexpression2 OR someexpression3 OR someexpression4 OR someexpression5
The string can't contain more than 3 of these expressions so I need to retrieve everything after someexpression3.
After the split I would need the following "OR someexpression4 OR someexpression5", the full string will always be different lengths so I need something dynamic in order to capture the last part of the string.
Without further information on how danymic your splitting should be the following code will cover your requirement:
'Some UnitTest
Dim toSplit As String = "someexpression1 OR someexpression2 OR someexpression3 OR someexpression4 OR someexpression5"
Dim actual = GetLastExpressions(toSplit)
Dim expected = "OR someexpression4 OR someexpression5"
Assert.AreEqual(expected, actual)
toSplit = "requirement OR is OR weird"
actual = GetLastExpressions(toSplit)
expected = ""
Assert.AreEqual(expected, actual)
'...
Private Function GetLastExpressions(expression As String, Optional splitBy As String = "OR", Optional numberToSkip As Integer = 3)
Dim expr As String = ""
Dim lExpressions As IEnumerable(Of String) = Nothing
Dim aSplit = expression.Split({expression}, StringSplitOptions.None)
If aSplit.Length > numberToSkip Then
lExpressions = aSplit.Skip(numberToSkip)
End If
If lExpressions IsNot Nothing Then
expr = splitBy & String.Join(splitBy, lExpressions)
End If
Return expr
End Function
Spoke to a friend of mine who suggested this and it works fine;
Dim sline As String = MyString
Dim iorcount As Integer = 0
Dim ipos As Integer = 1
Do While iorcount < 17
ipos = InStr(ipos, sline, "OR")
ipos = ipos + 2
iorcount = iorcount + 1
Loop
MsgBox(Mid(sline, ipos))

Read and change combo-box selected item with 4 different possible values

I have a multi-line textbox that the user can type into; the contents of which are supposed to drive the currently selected item in a combobox.
I have existing code that works for two items currently (Yes & No); however, I now need to make this extend to supporting four items. This is also updated by a timer every 3 seconds, in case if the user manually updated the text. The combobox cannot be typed in, instead it has preset selections.
Also the program is designed to edit properties files.
I'm a little unsure on how to go about doing so.
This is what works for 2 item changes:
Dim lines as Textbox1.lines()
Dim ach_tr As String = "announce-player-achievements=" 'stuff to be replaced by string ach_ttr
Dim ach_ttr As String = "" 'empty string to delete string ach_tr
Dim ach As String = lines(My.Settings.AnnouncePlayerAchievements)'line of string ach_tr
ach = ach.Replace(ach_tr, ach_ttr)'removes string ach_tr and leaves the value
If ach = "true" Then
achievements.SelectedItem = "Yes"
Else
achievements.SelectedItem = "No"
End If
I've tried these for 4 items:
Dim lines as Textbox1.lines()
Dim diff_tr As String = "difficulty="
Dim diff_ttr As String = ""
Dim diff As String = lines(My.Settings.Difficulty)
diff = diff.Replace(diff_tr, diff_ttr)
If diff = "0" Then
achievements.SelectedItem = "Peaceful"
End If
If diff = "1" Then
achievements.SelectedItem = "Easy"
End If
If diff = "2" Then
achievements.SelectedItem = "Normal"
End If
If diff = "3" Then
achievements.SelectedItem = "Hard"
End If
And This one:
Dim lines as Textbox1.lines()
Dim diff_tr As String = "difficulty="
Dim diff_ttr As String = ""
Dim diff As String = lines(My.Settings.Difficulty)
diff = diff.Replace(diff_tr, diff_ttr)
If diff = "0" Then
achievements.SelectedItem = "Peaceful"
Else
If diff = "1" Then
achievements.SelectedItem = "Easy"
Else
If diff = "2" Then
achievements.SelectedItem = "Normal"
Else
If diff = "3" Then
achievements.SelectedItem = "Hard"
End If
End If
End If
End If
You could do something akin to:
var difficultyMap = new Dictionary<string,string>
{
{"0", "Peaceful"},
{"1", "Easy"},
{"2", "Normal"},
{"3", "Hard"}
};
difficultyCombo.Items = difficultyMap.Values;
updateTimer.Tick += (s,e) => {
var text = inputTextBox.Text;
string found;
if (!difficultyMap.TryGetValue(text))
{
MessageBox.Show("unknown difficulty");
return;
}
difficultyCombo.SelectedItem = found;
};
This is in C# as I don't know VB very well, but the core concepts should map, I'm also not sure of your exact implementation or requirements, in essence I've done the following:
Created a dictionary that goes from the "numeric" difficulty type to the display type for the combo
Populated the combo using the display values from the dictionary
Whenever the update timer fires, I:
Get the text from the textbox
Try to find the matching difficulty in the dictionary
Display an error or update the combo
Adding n number of items to the combo and text input is trivial now, as you just add a new entry to the dictionary.
Edit: For future reference Heres a more compact version which works as well:
Public LineNum As Globals.LineNumEnum
Dim serveriptr As String = ("server-ip=")
Dim sipc As String = PropView.OutputRTF.Lines(LineNum.SerIP)
sipc = sipc.Replace(serveriptr, Nothing)
I found my problem. I was trying to change the wrong combobox lol. well at least I learned about dictionaries and the select case. Well thanks for your time.
This is the correct code lol:
Dim diff_tr As String = "difficulty="
Dim diff_ttr As String = ""
Dim diff As String = lines(My.Settings.Difficulty)
diff = diff.Replace(diff_tr, diff_ttr)
If diff = "0" Then
difficulty.SelectedItem = "Easy"
ElseIf diff = "1" Then
difficulty.SelectedItem = "Easy"
ElseIf diff = "2" Then
difficulty.SelectedItem = "Normal"
ElseIf diff = "3" Then
difficulty.SelectedItem = "Hard"
End If

Getting the character that inside the brackets

This is my string:
Dim value as string = "IR_10748(1).jpg"
How can I get this number 1 into another variable? I am thinking to use split.
How I can use to get this value in vb.net?
See String.Substring(Integer, Integer) and String.IndexOf(String).
Dim value As String = "IR_10748(1).jpg"
Dim startIndex As Integer = value.IndexOf("(") + 1
Dim length As Integer = value.IndexOf(")") - startIndex
Dim content As String = value.Substring(startIndex, length)
Regular expressions might be cleaner. This should work:
dim Result as string = Regex.Match(value, "(?<=\().*(?=\))").Value
It'll extract one or more characters contained between the parentheses.
Try this:
Dim value as String = "IR_10748(1).jpg"
Dim splitStrings() as String
'Split on either opening or closing parenthesis -
'This will give 3 strings - "IR_10748","1",".jpg"
splitStrings = value.Split(New String() {"(",")"}, StringSplitOptions.None)
'Parse as integer if required
Dim i as Integer
i = Integer.Parse(splitStrings(1))
Demo
It's not the prettiest, but this gets "1" using Remove and Split :
Dim value as String = "IR_10748(1).jpg"
Dim num As String = value.Remove(0, value.IndexOf("(") + 1).Split(")")(0)
That gives num = "1"
You can get the number more reliably than using String.Split. You'll want to use LastIndexOf to get the final opening parenthesis just in case you have a filename like "a(whatever)(1).ext", and you should inspect the filename without its extension, in case you have a filename like "a(1).(9)":
Dim value As String = "IR_10748(1).jpg"
Dim fn = Path.GetFileNameWithoutExtension(value)
Dim lastOpen = fn.LastIndexOf("(")
If lastOpen >= 0 Then
Dim length = fn.IndexOf(")", lastOpen + 1) - lastOpen - 1
If length >= 1 Then
Dim numAsString = fn.Substring(lastOpen + 1, length)
Console.WriteLine(numAsString)
ElseIf length = 0 Then
' do something if required
Console.WriteLine("No number in the parentheses.")
Else
' do something if required
Console.WriteLine("No closing parenthesis.")
End If
Else
' do something if required
Console.WriteLine("No opening parenthesis.")
End If

How do I create a loop statement that finds the specific amount of characters in a string?

Beginner here, bear with me, I apologize in advance for any mistakes.
It's some homework i'm having a bit of trouble going about.
Overall goal: outputting the specific amount of characters in a string using a loop statement. Example being, user wants to find how many "I" is in "Why did the chicken cross the road?", the answer should be 2.
1) The form/gui has 1 MultiLine textbox and 1 button titled "Search"
2) User enters/copys/pastes text into the Textbox clicks "Search" button
3) Search button opens an InputBox where the user will type in what character(s) they want to search for in the Textbox then presses "Ok"
4) (where I really need help) Using a Loop Statement, The program searches and counts the amount of times the text entered into the Inputbox, appears in the text inside the MultiLine Textbox, then, displays the amount of times the character showed up in a "messagebox.show"
All I have so far
Private Sub Search_btn_Click(sender As System.Object, e As System.EventArgs) Handles Search_btn.Click
Dim counterInt As Integer = 0
Dim charInputStr As String
charInputStr = CStr(InputBox("Enter Search Characters", "Search"))
I would use String.IndexOf(string, int) method to get that. Simple example of concept:
Dim input As String = "Test input string for Test and Testing the Test"
Dim search As String = "Test"
Dim count As Integer = -1
Dim index As Integer = 0
Do
index = input.IndexOf(search, index) + 1
count += 1
Loop While index > 0
count is initialized with -1 because of do-while loop usage - it will be set to 0 even if there is no pattern occurrence in input string.
Try this Code
Dim input As String = "Test input string for Test and Testing the Test"
Dim search() As String = {"Te"}
MsgBox(input.Split(input.Split(search, StringSplitOptions.None), StringSplitOptions.RemoveEmptyEntries).Count)
Concept: Increment the count until the input containing the particular search string. If it contains the search string then replace the first occurance with string.empty (In String.contains() , the search starts from its first index, that is 0)
Dim input As String = "Test input string for Test and Testing the Test"
Dim search As String = "T"
Dim count As Integer = 0
While input.Contains(search) : input = New Regex(search).Replace(input, String.Empty, 1) : count += 1 : End While
MsgBox(count)
Edit:
Another solution:
Dim Input As String = "Test input string for Test and Testing the Test"
Dim Search As String = "Test"
MsgBox((Input.Length - Input.Replace(Search, String.Empty).Length) / Search.Length)
try this code.... untested but i know my vb :)
Function lol(ByVal YourLine As String, ByVal YourSearch As String)
Dim num As Integer = 0
Dim y = YourLine.ToCharArray
Dim z = y.Count
Dim x = 0
Do
Dim l = y(x)
If l = YourSearch Then
num = num + 1
End If
x = x + 1
Loop While x < z
Return num
End Function
Its a function that uses its own counter... for every character in the string it will check if that character is one that you have set (YourSearch) and then it will return the number of items that it found. so in your case it would return 2 because there are two i's in your line.
Hope this helps!
EDIT:
This only works if you are searching for individual Characters not words
You can try with something like this:
Dim sText As String = TextBox1.Text
Dim searchChars() As Char = New Char() {"i"c, "a"c, "x"c}
Dim index, iCont As Integer
index = sText.IndexOfAny(searchChars)
While index >= 0 Then
iCont += 1
index = sText.IndexOfAny(searchChars, index + 1)
End While
Messagebox.Show("Characters found " & iCont & " times in text")
If you want to search for words and the times each one is appearing try this:
Dim text As String = TextBox1.Text
Dim wordsToSearch() As String = New String() {"Hello", "World", "foo"}
Dim words As New List(Of String)()
Dim findings As Dictionary(Of String, List(Of Integer))
'Dividing into words
words.AddRange(text.Split(New String() {" ", Environment.NewLine()}, StringSplitOptions.RemoveEmptyEntries))
findings = SearchWords(words, wordsToSearch)
Console.WriteLine("Number of 'foo': " & findings("foo").Count)
With this function used:
Private Function SearchWords(ByVal allWords As List(Of String), ByVal wordsToSearch() As String) As Dictionary(Of String, List(Of Integer))
Dim dResult As New Dictionary(Of String, List(Of Integer))()
Dim i As Integer = 0
For Each s As String In wordsToSearch
dResult.Add(s, New List(Of Integer))
While i >= 0 AndAlso i < allWords.Count
i = allWords.IndexOf(s, i)
If i >= 0 Then dResult(s).Add(i)
i += 1
End While
Next
Return dResult
End Function
You will have not only the number of occurances, but the index positions in the file, grouped easily in a Dictionary.

How to get an array to display all its values at once

Here is some sample code:
Dim arrValue(3) as Integer
arrValue(0) = 5
arrValue(1) = 4
arrValue(2) = 7
arrValue(3) = 1
How can I display those four values next to each other.
More specifically, given those values how can I make txtValue.Text = 5471
Edit:
The idea I had would be to use some sort of function to append each one to the end using a loop like this:
Dim finalValue
For i As Integer = 3 To 0 Step -1
arrValue(i).appendTo.finalValue
Next
Obviously that code wouldn't work though the premise is sound I don't know the syntax for appending things and I'm sure I wouldn't be able to append an Integer anyway, I would need to convert each individual value to a string first.
Another method is to use String.Join:
Sub Main
Dim arrValue(3) as Integer
arrValue(0) = 5
arrValue(1) = 4
arrValue(2) = 7
arrValue(3) = 1
Dim result As String = String.Join("", arrValue)
Console.WriteLine(result)
End Sub
If I understand your question correctly, you can use StringBuilder to append the values together.
Dim finalValue as StringBuilder
finalValue = new StringBuilder()
For i As Integer = 3 To 0 Step -1
finalValue.Append(arrValue(i))
Next
Then just return the finalValue.ToString()
Convert the integers to strings, and concatenate them:
Dim result as String = ""
For Each value as Integer in arrValue
result += value.ToString()
Next
Note: using += to concatenate strings performs badly if you have many strings. Then you should use a StringBuilder instead:
Dim builder as New StringBuilder()
For Each value as Integer in arrValue
builder.Append(value)
Next
Dim result as String = builder.ToString()
for i = lbound(arrValue) to ubound(arrValue)
ss=ss & arrValue(i)
next i
end for
debug.print ss
Dim value as string = ""
For A As Integer = 1 To Begin.nOfMarks
value += "Mark " & A & ": " & (Begin.Marks(A)) & vbCrLf
Next A