Proper Casing of Letters - vb.net

I have a Problem here in my casing function.
I used replace to change the all conjunction into a lower but still i have an error>
Private Function UpCsing(ByVal sValue As String) As String
Dim toConvert As String() = sValue.Split(" ")
Dim lst As New List(Of String)
For i As Integer = 0 To toConvert.Length - 1
Dim converted As String = ""
If toConvert(i).Contains("^") Then
converted = toConvert(i).ToUpper.Replace("^", "")
Else
converted = StrConv(toConvert(i), VbStrConv.ProperCase).Replace("^", "")
End If
lst.Add(converted)
Next
Dim ret As String = ""
For i As Integer = 0 To lst.Count - 1
If i = 0 Then
ret = lst(0)
Else
ret += " " + lst(i)
End If
Next
Return ret.Replace(" For ", " for ").Replace(" In ", " in ").Replace(" Of ", " of ").Replace(" And ", " and ").Replace(" And/Or ", " and/or ").Replace(" By ", " by ") _
.Replace(" By ", " by").Replace(" 2Nd ", " 2nd ").Replace(" 3Rd ", " 3rd ").Replace(" At ", " at ").Replace("And/Or ", "and/or ").Replace("1St", "1st").Replace("2Nd", "2nd").Replace("3Rd", "3rd") _
.Replace("At ", "at ").Replace(" At", " at").Replace(" Of", " of").Replace(" & ", " and ").Replace("Poc", "POC").Replace(" As ", " as ") _
.Replace("C/O", "c/o").Replace("$ ", "$").Replace(" And/Or ", " and/or ")
End Function
error sample:
'For' should be 'for' but the word 'Forward' must be 'Forward'
by my output change it into 'forward'
Example 'For the main event and for us to forward' the output should be 'For the Main Event and for us to Forward'

I tried with this code:
MessageBox.Show(UpCsing("for kelvzy sake I am paying^ this forward... forward^ for-ward..."))
And I get the correct result:
For Kelvzy Sake I Am PAYING This Forward... FORWARD For-Ward...
OK
Edit:
Example 'For the main event and for us to forward' the output should
be 'For the Main Event and for us to Forward'
Your code outputs Forward with a capital F, which exactly what you expect.
Edit 2:
The reason is because all words that are not prefixed/appended with ^ are converted to ProperCase with this line of code:
converted = StrConv(toConvert(i), VbStrConv.ProperCase).Replace("^", "")
Tip: there is no need to replace ^ with "" because words converted to ProperCase are not refixed/appended with ^.

Related

Finding the position of a specified string in another string

I need to find the position of a changing specified word in a string, and I need it to be very specific so it doesn't include words without spaces so say if I was looking for the word 'Hi' It would only return true if it was checking 'Hi' and not 'HiExample'.
Code:
Dim userString As String = userInput.Text
userString = userString.ToLower()
Dim d As New Dictionary(Of String, Integer)
Dim wordString = userString.ToLower().Split(" "c)
Dim iList As New List(Of String)()
For Each word In wordString
If d.ContainsKey(word) Then
d(word) += 1
iList.Add(word)
Else
d.Add(word, 1)
End If
Next
For Each de In d
For i As Integer = 0 To wordString.Count - 1
Dim index As Integer = userString.IndexOf(de.Key)
output.Text &= "Word: " & de.Key & " Occurrence: " & de.Value & " Position: " & GET POSTION OF EACH WORD HERE & Environment.NewLine
Next
Next
Checking for upper case or lower case will not be necessary as I have already converted the string into lower case.
Thanks,
Matt
you can try Regex
For Each de In d
Dim index As Integer = Regex.Matches(userString, "(?<=^|\b|\s)" & Regex.Escape(de.Key) & "(?=\s|\b|$)")(0).Index
Console.WriteLine("Word: " & de.Key & " Occurrence: " & de.Value & " Position: " & index)
Next
this might get you started

Visual Basic invalid cast runtime error

I'm new at Visual Basic, doing an assignment right now. This is the code I have
Sub Main()
Console.Write("Please let me know your nickname: ")
Dim name As String = Console.ReadLine()
Console.WriteLine("Thank you " + name + "!")
Console.WriteLine()
Console.Write("How many litres " + name + "<only whole litres please>? ")
Dim litres As Integer = Console.ReadLine()
Console.Write("Premium quality? <y/n>: ")
Dim ans As Char = Console.ReadLine()
Dim prem As Boolean
If ans = "y" Then
prem = True
ElseIf ans = "n" Then
prem = False
End If
Console.WriteLine()
Console.WriteLine("WELCOME TO APU'S GAS STATION")
Console.Write("Quality: ")
If prem = True Then
Console.Write("Premium")
Else : Console.Write("Regular")
End If
Dim price As Double = 12.44
Console.WriteLine("Quantity <l>: " + litres)
Console.WriteLine("Price per l: " + price)
Console.WriteLine("Sum to pay: " + litres * price)
Console.ReadLine()
End Sub
At runtime I can input all data no problem, but then I get an error that I can roughly translate to "invalid cast of the string "Quantity : " to type 'Double'.
I'm not so sure what is going on, would appreciate pointers.
to avoid this problem you can use
Console.WriteLine("Quantity <l>: " + litres.ToString)
Or you can use
Console.WriteLine("Quantity <l>: " + CStr(price))
I fixed your code, this should work :
Sub Main()
Console.Write("Please let me know your nickname: ")
Dim name As String = Console.ReadLine()
Console.WriteLine("Thank you " & name & "!")
Console.WriteLine()
Console.Write("How many litres " & name & "<only whole litres please>? ")
Dim litres As Integer = Console.ReadLine()
Console.Write("Premium quality? <y/n>: ")
Dim ans As Char = Console.ReadLine()
Dim prem As Boolean
If ans = "y" Then
prem = True
ElseIf ans = "n" Then
prem = False
End If
Console.WriteLine()
Console.WriteLine("WELCOME TO APU'S GAS STATION")
Console.Write("Quality: ")
If prem = True Then
Console.Write("Premium")
Else : Console.Write("Regular")
End If
Dim price As Double = 12.44
Console.WriteLine("Quantity <l>: " & litres)
Console.WriteLine("Price per l: " & price)
Console.WriteLine("Sum to pay: " & (litres * price))
Console.ReadLine()
End Sub

VB.net string join, adds unneeded space

Having some issues in vb.net string to join two strings together for output to a txt document. My text document is getting an extra space between the two strings I join. This should not be happening.
If System.IO.File.Exists(path) = True Then
' Create a file to write to.
Dim sw As StreamWriter = System.IO.File.CreateText(path)
sw.WriteLine("Attribute VB_Name = " & Chr(34) & "KbTest" & Chr(34))
sw.WriteLine("")
sw.WriteLine("Public Sub DoKbTest()")
sw.WriteLine("'code here")
sw.WriteLine("Dim catia")
sw.WriteLine("set catia = GetObject(, " & Chr(34) & "CATIA.Application" & Chr(34) & ")")
sw.WriteLine("Dim partDocument1")
sw.WriteLine("Set partDocument1 = catia.ActiveDocument")
sw.WriteLine("Dim part1")
sw.WriteLine("Set part1 = partDocument1.Part")
sw.WriteLine("Dim hybridShapeFactory1")
sw.WriteLine("Set hybridShapeFactory1 = part1.HybridShapeFactory")
sw.WriteLine("Dim hybridShapeDirection1")
sw.WriteLine("Set hybridShapeDirection1 = hybridShapeFactory1.AddNewDirectionByCoord(1#, 2#, 3#)")
sw.WriteLine("Dim hybridBodies1")
sw.WriteLine("Set hybridBodies1 = part1.HybridBodies")
sw.WriteLine("Dim hybridBody1")
sw.WriteLine("Set hybridBody1 = hybridBodies1.Item(" & Chr(34) & "PointSetx" & Chr(34) & ")")
sw.WriteLine("dim skteches1")
sw.WriteLine("Set sketches1 = hybridBody1.HybridSketches")
sw.WriteLine("Dim sketch1")
sw.WriteLine("Set sketch1 = sketches1.Item(" & Chr(34) & "Sketch.1" & Chr(34) & ")")
sw.WriteLine("Dim reference1")
sw.WriteLine("Set reference1 = part1.CreateReferenceFromObject(sketch1)")
sw.WriteLine("Dim hybridShapeExtremum1")
sw.WriteLine("Set hybridShapeExtremum1 = hybridShapeFactory1.AddNewExtremum(reference1, hybridShapeDirection1, 1)")
sw.WriteLine("hybridBody1.AppendHybridShape hybridShapeExtremum1")
sw.WriteLine("Dim reference2")
Dim lessOneCount As String
Dim spacing As Double = 0
Dim count As String
Dim setString As String
'loop
THIS IS THE PART OF THE CODE THAT IS ADDING EXTRA SPACES
For i = 1 To numbOfPoints Step 1
count = Str(i)
count.Replace(" ", "")
MsgBox(count)
If i < 2 Then
lessOneCount = "hybridShapeExtremum1"
Else
lessOneCount = "HybridShapePointOnCurve" + Str(i - 1)
End If
sw.WriteLine("reference2 = part1.CreateReferenceFromObject(" + lessOneCount + ")")
setString = "Dim hybridShapePointOnCurve" + count
sw.WriteLine(setString)
setString = "hybridShapePointOnCurve" + count + " = hybridShapeFactory1.AddNewPointOnCurveWithReferenceFromDistance(reference1, reference2, spacing, False)"
sw.WriteLine(setString)
setString = "hybridShapePointOnCurve" + count + ".DistanceType = 1"
sw.WriteLine(setString)
setString = "hybridBody1.AppendHybridShape(hybridShapePointOnCurve" + count + ")"
sw.WriteLine(setString)
Next
sw.WriteLine("End Sub")
sw.Flush()
sw.Close()
End If
Sample output:
Dim hybridShapePointOnCurve 2
SHOULD be:
Dim hybridShapePointOnCurve2
What modifications should I make to the way I join strings?
Thanks!
Realized my comment didn't answer your question completely, so a few things:
The String.Replace method doesn't work like you think it does. Saying count.Replace(" ", "") doesn't actually change the variable count; the function actually returns a new string. For it work like you want, you would need to do count = count.Replace(" ", "").
Consider using a StringBuilder instead of concatenating a bunch of strings together. It will greatly improve performance. When using the StringBuilder class, you also wouldn't need to write to the StreamWriter until the very end, simply by calling sw.Write(stringBuilderObject.ToString())
I haven't used VB.NET in a while, but I would check what Str(i) returns. Instead of using VB functions, consider using .NET functions by saying count = i.ToString(). According to Sky, the Str function indeed returns a space because it reserves it for the negative sign. Based on this, I would use the .ToString() method instead.
I spoke to quickly in my comment, the Str function reserves room for the sign, since it is a positive number there is no sign, if it was negative there would be a minus sign there. Try Trim(Str(i)) instead
From above link(emphasis mine):
This example uses the Str function to return a String representation of a number. When a positive number is converted to a string, a leading space is always reserved for its sign.

Display check box selections in one string (Visual Basic)

Trying to get the results of all selected items to display in one message box string. I have this so far, which I know is wrong. If it matters, this list is filled via a text file and objects.
Dim cBike As String = "
For Each cBike In clbBikes.Items
cBike = clbBikes.SelectedItem & ", "
Next
MsgBox(("Your selection of: " & cBike))
Help please, my lecturer is taking forever and helping those who need it more.
You probably meant CheckedItems:
Dim cBike As String = ""
For Each chk As String In clbBikes.CheckedItems
cBike &= chk & ", "
Next
MessageBox.Show("Your selection of: " & cBike)
You need to actually concatenate the strings:
For Each cBike In clbBikes.Items
cBike = cBike + clbBikes.SelectedItem & ", "
Next
You need to then also remove the last comma
If (xml.Length > 2) Then
cBike = cBike.Remove(cBike.Length - 2, 2)
End If

Email a table using VB.Net

I need to send an email with a table that has variable values in each cell. I can do this using any method (html via email, an excel/word table, etc.). The only hitch is due to the restrictions of the Emailer program and System.Net.Mail import, it has to be a string.
Here's what I have so far:
Imports DelayEmailer.DelayTrackerWs
Imports System.Configuration
Public Class DelayEmailer
Public Shared Sub Main()
Dim ws As New DelayTrackerWs.DelayUploader
Dim delays As DelayTrackerWs.Delay()
Dim emailer As New Emailer()
Dim delaystring As String
delays = ws.SearchDelaysDate(DelayTrackerWs.AreaEnum.QT, DelayTrackerWs.UnitEnum.QT, Now.AddDays(-1), Now)
delaystring = "Delays" & vbNewLine
delaystring &= "Facilty Start Time Status Category Reason Comment"
For i = 0 To delays.Length - 1
delaystring &= vbNewLine & delays(i).Facility & " "
delaystring &= FormatDateTime(delays(i).DelayStartDateTime, DateFormat.ShortDate) & " "
delaystring &= FormatDateTime(delays(i).DelayStartDateTime, DateFormat.ShortTime) & " "
'delaystring &= delays(i).DelayDuration & " "
delaystring &= delays(i).Status & " "
delaystring &= delays(i).CategoryCode & " "
delaystring &= delays(i).ReasonCode & " "
delaystring &= delays(i).Comment
Next
emailer.Send(ConfigurationManager.AppSettings("EmailList"), "delays", delaystring)
End Sub
As you can see, I currently have just a bunch of concatenated strings that line up if the values of each delays(i) are the same. The other problem is that this needs to be easily viewable via mobile devices and with the strings, it wraps and gets really unreadable. A table here should fix this.
You can send html email from .NET using MailMessage and SmtpClient classes, create an email template as string and set MailMessage's IsBodyHtml property to true:
Dim strHeader As String = "<table><tbody>"
Dim strFooter As String = "</tbody></table>"
Dim sbContent As New StringBuilder()
For i As Integer = 1 To rows
sbContent.Append("<tr>")
For j As Integer = 1 To cols
sbContent.Append(String.Format("<td>{0}</td>", YOUR_TD_VALUE_STRING))
Next j
sbContent.Append("</tr>");
Next i
Dim emailTemplate As String = strHeader & sbContent.ToString() & strFooter
...