Create a function that separates the characters of a word by symbols - vb.net

I want to create a function where, for example, if I put the word visual in the input box I have to select from the ComboBox one of these 3 symbols: space, . , or *, in the output box I want the result of the word visual to come out like this: v.i.s.u.a.l or v i s u a l
I already know how to output a result that separates the string by a space but I don't know how to do it using a ComboBox with 3 symbols
This is the code I used for separating with a space
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim n As Integer
Dim str As String = "mis programing II"
Dim str2 As String = ""
Dim cc As String
For i = 1 To Len(str)
cc = Mid(str, i, 1)
str2 = str2 & cc & " "
Next
MsgBox(str2)
End Sub
End Class

You can use String.Join like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String = "mis programing II"
Dim str2 As String = String.Join(str.ToCharArray(), ComboBox1.Text)
MsgBox(str2)
End Sub
I assumed the seperator has been selected in the ComboBox. Else, replace ComboBox1.Text with the seperator you want to use.
Update
Thanks to #JQSOFT, I just confirmed that String.Join does not work on Char arrays. Well here's another solution.
Dim str As String = "mis programing II"
Dim listX As New List(Of String)
Dim act As Action(Of Char) = Sub(c) listX.Add(CStr(c))
For Each c As Char In str.ToCharArray()
act.Invoke(c)
Next
Dim str2 As String = String.Join(".", listX.ToArray)
Console.WriteLine(str2)

Nice exercise:
Can be done using LINQ as follows:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String = txtInput.Text '"mis programing II" for this example..
Dim sep As Char
'Validate your inputs:
If String.IsNullOrWhiteSpace(str) OrElse
Not Char.TryParse(cmbSep.Text, sep) Then
Return
End If
'and in one line:
Dim str2 = String.Join("", str.Split(" "c).
SelectMany(Function(x) x.ToCharArray.Append(" "c)).
Select(Function(x) $"{x}{If(Char.IsWhiteSpace(x), " ", sep)}")).
Replace($"{sep} ", " ").Trim
MessageBox.Show(str2)
End Sub
If you are not allowed to use LINQ, then the next snippet will do the same:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String = txtInput.Text '"mis programing II" for this example..
Dim sep As Char
'Validate your inputs:
If String.IsNullOrWhiteSpace(str) OrElse
Not Char.TryParse(cmbSep.Text, sep) Then
Return
End If
Dim str2 As New StringBuilder
For Each word In str.Split(" "c)
For i = 0 To word.Length - 2
str2.Append(word(i)).Append(sep)
Next
str2.Append(word(word.Length - 1)).Append(" ")
Next
MessageBox.Show(str2.ToString.Trim)
End Sub
Some outputs:
m.i.s p.r.o.g.r.a.m.i.n.g I.I
m^i^s p^r^o^g^r^a^m^i^n^g I^I
m*i*s p*r*o*g*r*a*m*i*n*g I*I
m-i-s p-r-o-g-r-a-m-i-n-g I-I
m_i_s p_r_o_g_r_a_m_i_n_g I_I
m i s p r o g r a m i n g I I

Related

Separate and print all the words that have three letters

I need some help with a program that will extract from a RichTextBox all the words that have three letters and write the sum of these words?
I tried this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim strInput As String
strInput = RichTextBox1.Text
Dim strSplit() As String
strSplit = strInput.Split(CChar(" "))
MsgBox("Number of words: " & strSplit.Length)
End Sub
However this is only counting and I do not know how I can set a condition to count only words that have three letters.
Use LINQ to count the array items with length 3.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strInput As String
strInput = RichTextBox1.Text
Dim strSplit() As String
strSplit = strInput.Split(CChar(" "))
Dim count = From x In strSplit Where x.Length = 3
Dim sum = (From x In count Select x.Length).Sum()
MsgBox("Number of words: " & count.Count.ToString())
MsgBox("All the 3 letter words: " & String.Join(" ", count).ToString())
MsgBox("sum of the 3 letter words: " & sum.ToString())
End Sub

Get Character Of IndexOf

For an assigment my teacher is asking that we read from a file to find the characters of our name and place them at a label at the top of the form.
here is my code:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
searchFile = File.OpenText("AcademicEthicsandIntegrityStatement.txt")
Dim s As String = searchFile.ReadToEnd
Dim b As String = s.IndexOf("b"c)
Dim r As Integer = s.IndexOf("r"c)
Dim i As Integer = s.IndexOf("i"c)
Dim a As Integer = s.IndexOf("a"c)
Dim n As Integer = s.IndexOf("n"c)
Dim ec As Integer = s.IndexOf("e"c)
Dim bRead = GetChar(s, b)
Dim rRead = GetChar(s, r)
Dim iRead = GetChar(s, i)
Dim aRead = GetChar(s, a)
Dim nRead = GetChar(s, n)
Dim ecRead = GetChar(s, ec)
lblName.Text = bRead + rRead + iRead + aRead + nRead + nRead + ecRead
End Sub
The text that is reading into my lbl is "gmcaad" instead of "brianne"
Im sure that I am missing something here or there is a much easier way to do this. Any help is appreciated.
IndexOf returns a zero-based index.
GetChar accepts a one-based index.
For consistency,
if you want to use IndexOf, then use direct indexing instead of GetChar:
Dim bRead = s(b)
Dim rRead = s(r)
if you want to use GetChar, then use InStr instead of IndexOf that also returns one-based values.
Short Answer...case sensitive:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
With File.ReadAllText("AcademicEthicsandIntegrityStatement.txt")
For Each C As Char In "Brianne".ToCharArray
' Note this is case-sensitive because it uses a binary comparison
Dim Index As Integer = .IndexOf(C)
If Index >= 0 Then lblName.Text &= .Substring(Index, 1)
Next
End With
End Sub
... and non-case sensitive:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
With File.ReadAllText("AcademicEthicsandIntegrityStatement.txt")
For Each C As Char In "Brianne".ToCharArray
' Note this is not case-sensitive
Dim Index As Integer = .IndexOf(C.ToString, StringComparison.InvariantCultureIgnoreCase)
If Index >= 0 Then lblName.Text &= .Substring(Index, 1)
Next
End With
End Sub

Spliting the string and put value into textbox

I am using visual basic 2010.I have string of data in below format.I wanted to Split the comma seprated value and put into Individual text box.For The last
Temp_read:348,HV_Read:647,SPD:0,DIS:0". I would like to split values alone and put into text box.
can someone suggest me how can i do it. Is there any example code.
Public Class Form1
Dim selectedItem1 As String
Dim Data As String
Private Sub SMCB1_clientIP_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SMCB1_clientIP.TextChanged
End Sub
Private Sub SMCB1_Connect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SMCB1_Connect.Click
Dispay_Show.Text = SMCB1_clientIP.Text
Dispay_Show.Text = SMCB1_clientIP.Text & vbNewLine & SMCB1_Port.Text & vbNewLine
Data = "SMCB3,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,Temp_read:348,HV_Read:647,SPD:0,DIS:0"
Dispay_Show.Text = SMCB1_clientIP.Text & vbNewLine & SMCB1_Port.Text & vbNewLine & Data
Data.Split()
End Sub
Private Sub SMCB1_Disconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SMCB1_Disconnect.Click
End Sub
End Class
Image
Data = "SMCB3,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,Temp_read:348,HV_Read:647,SPD:0,DIS:0"
I have written code as below.There are 28 text boxes . value should get recorded into each text box. With below code i could record upto 28 value.
But From 24 the paramter contains
Temp_read:348,HV_Read:647,SPD:0,DIS:0"
Need to separate string ":" and put reading to particular text box.
Option Explicit On
Public Class Form1
Dim selectedItem1 As String
Dim Data As String
Dim WrdArray() As String
Dim line As String
Private Sub SMCB1_clientIP_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SMCB1_clientIP.TextChanged
End Sub
Private Sub SMCB1_Connect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SMCB1_Connect.Click
' Dispay_Show.Text = SMCB1_clientIP.Text
'Dispay_Show.Text = SMCB1_clientIP.Text & vbNewLine & SMCB1_Port.Text & vbNewLine
Data = "SMCB3,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,Temp_read:348,HV_Read:647,SPD:0,DIS:0"
' Dispay_Show.Text = SMCB1_clientIP.Text & vbNewLine & SMCB1_Port.Text & vbNewLine & Data
Dispay_Show.Text = Data
Dim strArray() As String
Dim intCount As Integer
Dim Tempr_read As String
Dim voltage As String
Dim SPD As String
Dim Dis_value As String
Data = "SMCB3,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,Temp_read:348,HV_Read:647,SPD:0,DIS:0"
strArray = Split(Data, ",")
SMCB1_Name.Text = strArray(0)
SMCB1_DeviceId.Text = strArray(1)
SMCB1_String1.Text = strArray(2)
SMCB1_String2.Text = strArray(3)
SMCB1_String3.Text = strArray(4)
SMCB1_String4.Text = strArray(5)
SMCB1_String5.Text = strArray(6)
SMCB1_String6.Text = strArray(7)
SMCB1_String7.Text = strArray(8)
SMCB1_String8.Text = strArray(9)
SMCB1_String9.Text = strArray(10)
SMCB1_String10.Text = strArray(11)
SMCB1_String11.Text = strArray(12)
SMCB1_String12.Text = strArray(13)
SMCB1_String13.Text = strArray(14)
SMCB1_String14.Text = strArray(15)
SMCB1_String15.Text = strArray(16)
SMCB1_String16.Text = strArray(17)
SMCB1_String17.Text = strArray(18)
SMCB1_String18.Text = strArray(19)
SMCB1_String19.Text = strArray(20)
SMCB1_String20.Text = strArray(21)
SMCB1_String21.Text = strArray(22)
SMCB1_String22.Text = strArray(23)
SMCB1_String23.Text = strArray(24)
SMCB1_String24.Text = strArray(25)
' Tempr_read = Split(Data(strArray(26),":")
SMCB1_Temp.Text = strArray(26)
SMCB1_Hvread.Text = strArray(27)
SMCB1_SPD.Text = strArray(28)
SMCB1_DIS.Text = strArray(29)
For intCount = LBound(strArray) To UBound(strArray)
Debug.Print(Trim(strArray(intCount)))
Next
End Sub
Private Sub SMCB1_Disconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SMCB1_Disconnect.Click
End Sub
End Class
I suggest using 2 instances of the InStrRev function - one for the colon and the other for the comma whilst looping backwards through the string and building your array.
In this way you will be able to capture the data to the right of the colon (and before the comma), yet disregard the label between the comma and the colon (if that is in fact what you intend to do).
Please hit me up if you would like a worked example.
Regards

How to pass all value of ListBox Control to a function?

I am writing a simple application to read the value a textbox and add to a listbox control . But i have to pass the listbox control to function . Any suggestion ?
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
test("E:\Satyajit.txt")
End Sub
Public Function test(ByVal filename As String)
Dim FILE_NAME As String = filename
Dim TextLine As String
Dim result As String = Path.GetFileName(FILE_NAME)
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
words = TextLine.Split(New Char() {","c})
ListBox1.Items.Add(words(3) & "," & words(4))
objItem = ListView1.Items.Add(words(3) & "," & words(4))
Loop
test1(ListBox1.Items)//pass the listbox value hare
End Function
Public Function test1(ByVal value As String)
Dim Fest As String = value
MsgBox(Fest)
End Function
You're passing the contents of a ListBox to a method that is just displaying them in a MsgBox(). There are two approaches you can do to accomplish what I think you're wanting.
You can pass ListBox.Items to the method and iterate through each item concatenating them into a single String or StringBuilder, then pass the String to the MsgBox(). This approach makes your method dependent on ListBoxItems.
You can iterate through ListBox.Items concatenating them into a single String or StringBuilder, then pass the String to your method. This makes your method a little more scalable.
I recommend approach #2, something like:
Dim MyListBox As New ListBox
MyListBox.Items.Add("Item1")
MyListBox.Items.Add("Item2")
MyListBox.Items.Add("Item3")
MyListBox.Items.Add("Item4")
MyListBox.Items.Add("Item5")
Dim sb As New StringBuilder
For Each Item In MyListBox.Items
sb.AppendLine(Item)
Next
Test1(sb.ToString())
The Test1 method would look like:
Public Sub Test1(ByVal value As String)
MsgBox(value)
End Sub
Results:
You could pass the whole control to the function:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim lstbox As New ListBox
lstbox.Items.Add("Hello")
lstbox.Items.Add("Second Item")
lstbox.Items.Add("Third Item")
MsgBox("The list contains: " & Length(lstbox) & " characters")
End Sub
Function Length(ByVal ctrl As ListBox) As Integer
Dim TotalNumberOfItems As Integer = 0
For Each item As String In ctrl.Items.ToString
TotalNumberOfItems += 1
Next
Return TotalNumberOfItems
End Function
or just its items
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim lstbox As New ListBox
lstbox.Items.Add("Hello")
lstbox.Items.Add("Second Item")
lstbox.Items.Add("Third Item")
MsgBox("The list contains: " & Length(lstbox.Items) & " characters")
End Sub
Function Length(ByVal col As ListBox.ObjectCollection) As Integer
Dim TotalNumberOfCharacters As Integer = 0
For Each item As String In col
TotalNumberOfCharacters += item.Length
Next
Return TotalNumberOfCharacters
End Function

Reading from and manipulating a .csv file

I have multiple .csv files for each month which go like:
01/04/2012,00:00,7.521527,80.90972,4.541667,5.774305,7,281.368
02/04/2012,00:00,8.809029,84.59028,6.451389,5.797918,7,274.0764
03/04/2012,00:00,4.882638,77.86806,1.152778,15.13611,33,127.6389
04/04/2012,00:00,5.600694,50.35417,-3.826389,15.27222,33,40.05556
The format is : Date in the form dd/mm/yy,Current time,Current temperature,Current humidity,Current dewpoint,Current wind speed,Current wind gust,Current wind bearing
The program needs to calculate the average for
temperature
humidity
wind speed
wind direction
and display them on a text box.
any ideas?
Here is what I have done so far...
Option Strict On
Option Explicit On
Imports System.IO
Imports System
Public Class Form1
Private Sub cmb1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmb1.SelectedIndexChanged
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnexit.Click
Me.Close()
End Sub
Private Sub btn1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndata.Click
'This is for August
If cmb1.SelectedIndex = 1 Then
TextBox1.Clear()
Using reader As New StreamReader("c://temp/DailyAug12log.csv")
Dim line As String = reader.ReadLine()
Dim avgTemp As Integer
Dim fields() As String = line.Split(",".ToCharArray())
Dim fileDate = CDate(fields(0))
Dim fileTime = fields(1)
Dim fileTemp = fields(2)
Dim fileHum = fields(3)
Dim fileWindSpeed = fields(4)
Dim fileWindGust = fields(5)
Dim fileWindBearing = fields(6)
While line IsNot Nothing
counter = counter + 1
line = reader.ReadLine()
End While
avgTemp = CInt(fields(2))
avgTemp = CInt(CDbl(avgTemp / counter))
TextBox1.Text = TextBox1.Text & "Month = August" & vbCrLf & "Temperature Average: " & avgTemp & vbCrLf
End Using
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim files() As String
files = Directory.GetFiles("C:\Temp", "*.csv", SearchOption.AllDirectories)
For Each FileName As String In files
cmb1.Items.Add(FileName.Substring(FileName.LastIndexOf("\") + 1, FileName.Length - FileName.LastIndexOf("\") - 1))
Next
End Sub
End Class
Private Class Weather
Public SampleTimeStamp AS Date
Public Temperature AS Double
Public Humidity As Double
Public WindSpeed AS Double
Public WindBearing AS Double
End Class
Sub Main
Dim samples = ReadFile("c://temp/DailyAug12log.csv")
Dim avgTemperature = samples.Average(Function(s) s.Temperature)
...
End Sub
Private Function ReadFile(ByVal fileName as String) AS List(Of Weather)
Dim samples As New List(Of Weather)
Using tfp As new TextFieldParser(filename)
tfp.Delimiters = new String() { "," }
tfp.TextFieldType = FieldType.Delimited
While Not tfp.EndOfData
Dim fields = tfp.ReadFields()
Dim sample As New Weather()
sample.SampleTimeStamp = Date.ParseExact(fields(0) & fields(1), "dd\/MM\/yyyyHH\:mm", CultureInfo.InvariantCulture)
sample.Temperature = Double.Parse(fields(2), CultureInfo.InvariantCulture)
sample.Humidity = Double.Parse(fields(3), CultureInfo.InvariantCulture)
sample.WindSpeed = Double.Parse(fields(4), CultureInfo.InvariantCulture)
sample.WindBearing = Double.Parse(fields(5), CultureInfo.InvariantCulture)
samples.Add(sample)
End While
Return samples
End Using
End Function
I would not use a this aprroach - if the order of the columns changes, your program will show wrong results.
I would use a good csv reader like http://kbcsv.codeplex.com/ and read the Data to a datatable. then you can calculate your resulting columns quite easily and reliablly, because you can adress each column like MyDatatable.Cooumns["Headername"].