Substring a Word from a Multiline Textboxes - vb.net

I want to do the following thing: if I have a Textbox1.Lines:
2
5
15
21
45
and I want to for example get the number left 15 and get the number right 15.
Output: Textbox2.Lines 15 21
5 15
How should I do this? example for the number 2 want substring 2 5
Module Module1
Public Function FirstWords(input As String,
count As Integer) As String
Dim words = count
For i As Integer = 0 To input.Length - 1
' Decrement word count when we reach a space.
If input(i) = " " Then
words -= 1
End If
' When no words remaining, return a substring to this point.
If words = 0 Then
Return input.Substring(0, i)
End If
Next
Return ""
End Function
how should i do this to work?

You can separate them into an array of strings with the Split function, like in this example:
Dim input as String = "2 5 15 21 45"
Dim numbers as String() = input.Split(" ")
For Each s as String In numbers
Console.WriteLine(s)
Next
You just have to figure out how to extract the numbers you want from the lot. Have fun!

Related

Issue learning For...Next loop

The following is an exercise I am having trouble with.
The button’s Click event procedure should display the number of integers from 14 to 23 in one of the labels and the sum of those integers in the other label. Code the procedure using the For…Next statement. Save the solution and then start and test the application. (The procedure should display the numbers 10 and 185.)
I'm able to display the sum 185 but not understanding how to display the amount of numbers (10) between 14 to 23. Any help is appreciated.
Public Class frmMain
Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
Dim intSum As Integer
For intNum As Integer = 14 To 23
lblShow.Text = lblShow.Text & intNum.ToString & " "
intSum += intNum
lblSum.Text = intSum.ToString
Next
End Sub
End Class
Just declare sum and count local variables and increment them appropriately in the For. You need only update the Label.Text once after the calculations have been done
Dim intSum As Integer
Dim intCount As Integer
For intNum As Integer = 14 To 23
intSum += intNum
intCount += 1
Next
lblSum.Text = intSum.ToString()
lblShow.Text = intCount.ToString()
I understand your homework has the For requirement, but .NET has some functionality built in which can produce a list of numbers, sum them, and count them.
Dim start = 14
Dim finish = 23
Dim numbers = Enumerable.Range(start, finish - start + 1)
lblSum.Text = numbers.Sum().ToString()
lblShow.Text = numbers.Count().ToString()
Both methods produce your required output
display the number of integers from 14 to 23
This can be interpreted in a couple of ways:
Display the count of integers between the two numbers (e.g. 23 - 14)
Display each individual integer between the two numbers (e.g. 14, 15, 16, etc.)
If it is the former, then simply subtract the larger number from the smaller number and display that value in a label:
LabelIntegerCount.Text = (23 - 147).ToString()
If it is the latter, then inside of your For/Next loop append the currently iterated counter to the label:
For intNum As Integer = 14 To 23
LabelIntegerCount.Text &= intNum.ToString() & Environment.NewLine
' ...
Next

two textbox intersect each line vbcrlf

Textbox1.Lines =
2
4
11
13
19
21
Textbox2.Lines =
3
5
14
17
26
29
In output (Textbox3.text) I want the following issue:
2 3
4 5
11 14
13 17
19 26
21 29
so how do I get this to work?
Dim linesx() As String = TxtStringNumP1.Lines
Dim linesy() As String = TxtStringNumP2.Lines
For x As Integer = 1 To linesx.Length - 1
For y As Integer = 1 To linesx.Length - 1
Dim strWords1 = linesx(y).Split(",")
Dim strWords2 = linesy(y).Split(",")
TextBoxO1.Text &= Val(strWords1(0)) + vbCrLf + Val(strWords2(0) & vbNewLine)
Next
Next
Remove the vbCrLf as you don't want a new line between the first value & the second. Then, you also don't want a second loop, otherwise you are looping through the values multiple times. You also don't need to split the values by commas if they aren't going to contain commas
Finally, the value needs to be appended to the text already in TextBox01 otherwise its value is just being replaced. The TextBox01.Clear() ensures that it is empty to begin with.
TextBox01.Clear()
Dim linesx() As String = TxtStringNumP1.Lines
Dim linesy() As String = TxtStringNumP2.Lines
For x As Integer = 0 To linesx.Length - 1
Dim strWords1 As String = linesx(x)
Dim strWords2 As String = linesy(x)
TextBoxO1.Text = TextBoxO1.Text & strWords1 & " " & strWords2 & vbCrLf
Next
The above code assumes both text boxes will have the same amount of lines. If this isn't the case, you will need to check that a line exists before trying to assign it to one of your strWords variables. You will also need to loop to the larger of the 2 Lines.Length

Fill combobox with time values

I want fill my combobox with time values like (08:00, 08:10, 08:20 until 09:50) step=10 minutes but the result is like (8:00, 8:10, 8:20, 8:30, 9:-20,9:-10, 9:00, 9:10, 9:20).
My code doesn't show the value like 8:40, 8:50 and he also show negative value like 9:-20, 9:-10).
So please how can I resolve this problem?
Heure_rdv.Items.Clear()
Dim nbr_minute2 As String
For i = 480 To 590 Step 10
Dim nbr_heure As Integer = cint(i / 60)
Dim nbr_minute As Integer = (i - (nbr_heure * 60))
nbr_minute2 = CStr(nbr_minute) + "0"
If ((i - (nbr_heure * 60)) = 0) Then
Heure_rdv.Items.Add(CStr(nbr_heure) + ":" + nbr_minute2)
Else
Heure_rdv.Items.Add(CStr(nbr_heure) + ":" + CStr(nbr_minute))
End If
Next
This is how I should do try it in VBA.
Should be similar in VB.NET
DIM i As Integer 'Counter 1
Dim ii As Integer 'Counter 2
' make 1st loop for hours
for i = 8 To 9
' mkae 2nd loop for minutes
for ii = 0 To 50 Step 10
'
Heure_rdv.Items.Add(i & ":" & ii)
next
next
This could be done with fewer lines of code using linq
Dim steps = Enumerable.Range(0,6)
Dim items as List(Of String) = new List(Of String)()
items.AddRange(steps.Select(Function(x) "08:" & (x * 10).ToString("D2")))
items.AddRange(steps.Select(Function(x) "09:" & (x * 10).ToString("D2")))
Heure_rdv.DataSource = items
First we create a list of integers from 0 to 5 (6 elements), then using these elements we create the strings required multiplying each element of the integer list by ten and converting the result to a two digit string. We do this one time for the 8 hour and one time for the 9. Finally we could set the combo datasource to the resulting list of strings.

Word input from one line in the textbox to another

I have 5 text boxes marked with NX1, NX2, NX3 .... NX5.
I have a Textbox marked with Textbox2 that contains lines like:
2 4 6 8 11
1 2 3 4 12
3 4 7 9 13
4 5 7 9 14
Is there a possibility to enter the first word / number from TextBox2 Lines (0) in NX1? i.e. First Word (number 2 in NX1), (Second Word) number 4 in NX2, number 6 in NX3 and number 8 in NX4. and so on.
I tried this:
Dim mytext As String
Dim counter As Integer
mytext = TextBox1.Text
For counter = 1 To Len(TextBox1.Text)
If Mid$(mytext, counter, 1) = " " Then
GoTo NextPart
End If
Next counter
NextPart:
MsgBox("'" + Mid$(mytext, 1, counter - 1) + "'")
MsgBox("'" + Mid$(mytext, 2, counter - 1) + "'")
Get the TextBox.Lines(0). That's the first line of text. If the text parts are separated by a white space, just Split() the text (white space is the default separator).
If it's not, specify the separator: Split("[SomeChar]"c).
You'll get 5 strings in a String() array. Assing String(0) to NX1 etc.
Dim FirstLine As String = TextBox2.Lines(0)
Dim AllParts As String() = FirstLine.Split()
NX1.Text = AllParts(0)
NX2.Text = AllParts(1)
'(...)
Repeat the same procedure if you need the other text lines.
You could also use LINQ to perform the string assignments:
AllParts.Select(Function(s, i) Me.Controls("NX" & (i + 1)).Text = s).ToList()
Or, assemble everything in one expression:
TextBox2.Lines(0).Split().Select(Function(s, i) Me.Controls("NX" & (i + 1)).Text = s).ToList()
A description of this method:
[TextBox].Lines(0) => Returns the first line of text in a TextBoxBase control
Split() => Splits the text content using the default separator.
Returns an array of String
Select((string, int)) => Selects each string returned by the Split() method and updates
the index of each iteration.
Performs an action: sets a control`s Text property.
ToList() => Materializes the Enumerable collection returned by Select()
If omitted, in this case, the iteration is performed just once
Me.Controls("NX" & (i + 1)).Text = s:
Returns a Form's Control which name is "NX" + a number and assigns a string to its Text property.
You can use String.Split() to split the string.
Dim columns = TextBox2.Lines(0).Split()
For i = 0 To columns.Length - 1
Controls.Item("NX" & (i + 1)).Text = columns(i)
Next
The Lines property of the TextBox returns a string array containing the lines of the entered text.
String.Split() with no parameters splits a string at white spaces and returns a string array containing the parts (the columns of the first lines in this case).
The Controls property of the form returns a controls collection. The indexed Item property of the controls collection accepts either an Integer index or a control name as String.

How do you convert a string into hexadecimal in VB.NET?

How do I convert a string from a textbox into hexadecimal?
I have only found ways in C#. Does VB.NET have the ability to do such a thing? If it can then I'd like to know how to convert string to hex and hex to string.
Dim val As String
val = "10"
Dim hexVal As Integer
hexVal = Convert.ToInt32(val, 16) //16 specifies the base
Console.WriteLine(hexVal)
This will display 16 which is the integer equivalent of the hexadecimal string "10".
You can convert an integer to a hexdecimal number easily by doing:
Convert.ToInt32(15, 16)
And to convert it back to an integer, you can do:
Integer.Parse("15f", System.Globalization.NumberStyles.HexNumber)
Public Function StrToHex(ByRef Data As String) As String
Dim sVal As String
Dim sHex As String = ""
While Data.Length > 0
sVal = Conversion.Hex(Strings.Asc(Data.Substring(0, 1).ToString()))
Data = Data.Substring(1, Data.Length - 1)
sHex = sHex & sVal
End While
Return sHex
End Function
Tried and tested code
Create this function by copy pasting it.
Function StringToHex(ByVal text As String) As String
Dim hex As String
For i As Integer = 0 To text.Length - 1
hex &= Asc(text.Substring(i, 1)).ToString("x").ToUpper
Next
Return hex
End Function
Use it like this
Debug.WriteLine(StringToHex("sim0n"))
Source
To convert into hexadecimal, use Convert.ToInt32(val, 16). Convert.ToInt32 supports limited bases, 2, 8, 10, and 16.
To convert into any base, use:
Public Shared Function IntToString(value As Integer, baseChars As Char()) As String
Dim result As String = String.Empty
Dim targetBase As Integer = baseChars.Length
Do
result = baseChars(value Mod targetBase) + result
value = value / targetBase
Loop While value > 0
Return result
End Function
The above function comes from this question. The C# to VB conversion was done using this.
Short and effective expression to display all characters of String s in hexadecimal form can be written using LINQ:
String.Join(" ", s.Select(Function(c) Conversion.Hex(AscW(c)).PadLeft(4, "0")).ToArray()))
Example:
For string ► fix it gives string 25BA 0020 0066 0069 0078.
Enjoy!
Please keep in mind this is Unicode-enabled, returning 4-digit hexadecimal value for every character, because old plain Non-Unicode ASCII is dead and you should no longer rely on it in any application.
In my humble opinion the code of Tilak seems OK, but is not.
The rounding of value / targetBase gives results that are too large.
By using Fix() the resulting integers will be as they should be.
I compliment Tilak for finding such a neat solution for the question.
In the accompanying code I will show how functions like IntToString can be tested easily.
The expected message in the message box is:
The old results are;
0 1 10 101 100 101 1010 1001 1000 1001 1010
0 1 1X 10 11 1XX 1X0 1X1 10X 100 101
0 1 X 1y 10 11 XX Xy X0 X1 XX
0 1 X 1y 1z 10 11 1X Xy Xz X0
The new results are;
0 1 10 11 100 101 110 111 1000 1001 1010
0 1 X 10 11 1X X0 X1 XX 100 101
0 1 X y 10 11 1X 1y X0 X1 XX
0 1 X y z 10 11 1X 1y 1z X0
The new results are better IMHO.
Public Sub test()
Dim numberCharacters As String = "01Xyz"
Dim messageText As String = "The old results are;" & vbNewLine
For loopCount As Integer = 1 To 2
If loopCount = 2 Then messageText &= "The new results are;" & vbNewLine
For baseLength As Integer = 2 To 5
Dim baseCharacters As Char() = _
Strings.Left(numberCharacters, baseLength).ToArray
For integerValue As Integer = 0 To 10
Dim resultText As String = _
Me.IntToString(integerValue, baseCharacters, loopCount = 2)
messageText &= resultText & " "
Next
messageText &= vbNewLine
Next
Next
Call MsgBox(berichtTekst & "The new results are better IMHO.")
End Sub
Public Function IntToString(value As Integer, baseChars As Char(), _
Optional newCode As Boolean = False) As String
Dim result As String = String.Empty
Dim targetBase As Integer = baseChars.Length
Do
result = baseChars(value Mod targetBase) & result
If newCode Then ' Improved code
value = Fix(value / targetBase)
Else ' Original code
value = value / targetBase
End If
Loop While value > 0
Return result
End Function
Hopefully this will help others.
I have more than 25 years experience as a programmer, mainly in RPG, Cobol, Synon, CL and Basic. I also know some Delphi, Pascal and C#. I am sure I can be a help to this community.
It makes me sad that I cannot comment to answers. Hopefully someone will add me some points, so that I can more easily help others from now on.
Because of this I add my comment to the answer of Tilak, dated may 8, 2012, as an answer. This is the first and hopefully the only time that I resort to this. Sorry for that, but I know no other way.