Trim last "," delimiter of a string in VB.NET - vb.net

This is my code:
With ad.Tables(2)
For i As Integer = 0 To .Rows.Count - 1
If .Rows(i)("name") & "" <> "" Then
temp &= .Rows(i)("name") & ", "
End If
Next
End With
temp = temp.Trim(",")
testing &= "&Name=" & temp & vbCrLf
With this is get a comma in the end of the string. But if I do
temp = temp.Trim.Trim(",")
all commas are deleted.
How do I keep all commas and only delete the last one?

temp = temp.TrimEnd(CChar(","))
That will do it and I think it is the easiest way.

temp = temp.Trim().Substring(0, temp.Length - 1)
or
temp = temp.Trim().Remove(temp.Length - 1)

You can avoid the Trim/extra character if you set a delimiter within the loop
Dim delimiter as string = ""
For i As Integer = 0 To .Rows.Count - 1
If .Rows(i)("name") & "" <> "" Then
temp &= delimiter & .Rows(i)("name")
delimiter = ","
End If
Next

The Trim() function has a Char() (static array of characters) parameter on it, you don't need to pass a Char explicitly.
' VB.Net Version
", Hello ^_^ ^_^ ,,, , ,, ,, ,".Trim({" "c, ","c})
//C# version
", Hello ^_^ ^_^ ,,, , ,, ,, ,".Trim({' ', ','})
Would produce the output
"Hello ^_^ ^_^"
The multi-parameter .Trim() removes the specified characters from both the beginning and the end of the string. If you want to only trim out the beginning or the end, use .TrimStart() or .TrimEnd() respectively.

This works:
dim AlarmStr as string="aaa , bbb , ccc , "
AlarmStr = AlarmStr.Remove(AlarmStr.LastIndexOf(","))

Check to see if the loop is done before adding the last comma. #cleaner
While dr.Read
For c As Integer = 0 To dr.FieldCount - 1
s.Append(dr(c).ToString.Trim)
'This line checks if the loop is ending before adding a comma
If (c < dr.FieldCount - 1) Then s.Append(",")
Next
s.Append(vbCrLf)
End While

I wonder, that based on the OP's code sample, nobody suggested to use String.Join or build an output with StringBuilder
Dim names As New List(Of String)
With ad.Tables(2)
For i As Integer = 0 To .Rows.Count - 1
' DataRow("columnName").ToString() returns value or empty string if value is DbNull
If .Rows(i)("name").ToString() <> "" Then
names.Add(.Rows(i)("name"))
End If
Next
End With
Dim temp As String = String.Join(", ", names)
testing &= "&Name=" & temp & vbCrLf
With LINQ and DataRow extension method .Field(Of T) code will look simpler
Dim names = ad.Tables(2).
AsEnumerable().
Select(row => row.Field<String>("name")).
Where(name => String.IsNullOrEmpty(name) = False)
Dim temp As String = String.Join(", ", names)
testing &= "&Name=" & temp & vbCrLf
If you go further you can(should) use StringBuilder for building a string and use Aggregate method to build string from the collection

I know that a little bit odd, but I found this works for me:
Visual Basic:
Every time: mystring = "today, I love go out , , , ," (less than five commas and spaces)
mystring.Trim.TrimEnd(",").Trim.TrimEnd(",").Trim.TrimEnd(",").Trim.TrimEnd(",").Trim.TrimEnd(",")

temp = temp.TrimEnd()
this trims the trailing spaces from a string.

Related

String.Replace() for quotation marks

I am trying to run the following line of code to replace the Microsoft Word quotes with ones our database can store. I need to work around users copying strings from Microsoft Word into my textareas.
instrText = instrText.Replace("“", """).Replace("”", """)
I am getting syntax errors for the number of arguments.
I have tried character escapes and a couple other ways of formatting the arguments with no luck.
This changes the 'smart' quotes from word,
'non standard quotes
Dim Squotes() As Char = {ChrW(8216), ChrW(8217)} 'single
Dim Dquotes() As Char = {ChrW(8220), ChrW(8221)} 'double
'build test string
Dim s As String = ""
For x As Integer = 0 To Squotes.Length - 1
s &= x.ToString & Squotes(x) & ", "
Next
For x As Integer = 0 To Dquotes.Length - 1
s &= (x + Squotes.Length).ToString & Dquotes(x) & ", "
Next
'replace
For Each c As Char In Squotes
s = s.Replace(c, "'"c)
Next
For Each c As Char In Dquotes
s = s.Replace(c, ControlChars.Quote)
Next
Try the following:
Private Function CleanInput(input As String) As String
DisplayUnicode(input)
'8216 = &H2018 - left single-quote
'8217 = &H2019 - right single-quote
'8220 = &H201C - left double-quote
'8221 = &H201D - right double-quote
'Return input.Replace(ChrW(&H2018), Chr(39)).Replace(ChrW(&H2019), Chr(39)).Replace(ChrW(&H201C), Chr(34)).Replace(ChrW(&H201D), Chr(34))
Return input.Replace(ChrW(8216), Chr(39)).Replace(ChrW(8217), Chr(39)).Replace(ChrW(8220), Chr(34)).Replace(ChrW(8221), Chr(34))
End Function
Private Sub DisplayUnicode(input As String)
For i As Integer = 0 To input.Length - 1
Dim lngUnicode As Long = AscW(input(i))
If lngUnicode < 0 Then
lngUnicode = 65536 + lngUnicode
End If
Debug.WriteLine(String.Format("char: {0} Unicode: {1}", input(i).ToString(), lngUnicode.ToString()))
Next
Debug.WriteLine("")
End Sub
Usage:
Dim cleaned As String = CleanInput(TextBoxInput.Text)
Resources:
ASCII table
C# How to replace Microsoft's Smart Quotes with straight quotation marks?
How to represent Unicode character in VB.Net String literal?
Note: Also used Character Map in Windows.
You have a solution that works above, but in keeping with your original form:
instrText = instrText.Replace(ChrW(8220), """"c).Replace(ChrW(8221), """"c)

Using Ms Access VBA, how do I check the value of a variable to see if it has a value other than "', "

I have a variable with a string...and I want to know if it contains any value other than single quote, comma and a space ("', ") I'm using vba in excel.
for example, i have a varible strA = "'test', 'player'"
I want to check to see if strA has any characters other than "', " (single quote, comma and space).
Thanks
Here is a strategy based on Count occurrences of a character in a string
I don't have vba handy, but this should work. The idea is to remove all these characters and see if anything is left. text represents your string that is being tested.
Dim TempS As String
TempS = Replace(text, " " , "")
TempS = Replace(TempS, "," , "")
TempS = Replace(TempS, "'" , "")
and your result is Len(TempS>0)
Another approach is to use recursion by having a base case of false if the string is empty, if the first character is one of the three call ourselves on the rest of the string, or if not the value is true. Here is the code
function hasOtherChars(s As String) As Boolean
hasOtherChars=false
if (len(s)=0) then
exit function
end if
Dim asciiSpace As Integer
asciiSpace = Asc(" ")
Dim asciiComma As Integer
asciiComma= Asc(",")
Dim asciiApostrophe As Integer
asciiApostrophe = Asc("'")
Dim c as Integer
c = Asc(Mid$(s, 1, 1))
if ((c=asciiSpace) or (c=asciiComma) or (c=asciiApostrophe)) then
hasOtherChars = hasOtherChars(Mid$(s,2))
else
hasOtherChars=true
end if
End function
Again I am borrowing from the other thread.

VB.NET - Delete excess white spaces between words in a sentence

I'm a programing student, so I've started with vb.net as my first language and I need some help.
I need to know how I delete excess white spaces between words in a sentence, only using these string functions: Trim, instr, char, mid, val and len.
I made a part of the code but it doesn't work, Thanks.
enter image description here
Knocked up a quick routine for you.
Public Function RemoveMyExcessSpaces(str As String) As String
Dim r As String = ""
If str IsNot Nothing AndAlso Len(str) > 0 Then
Dim spacefound As Boolean = False
For i As Integer = 1 To Len(str)
If Mid(str, i, 1) = " " Then
If Not spacefound Then
spacefound = True
End If
Else
If spacefound Then
spacefound = False
r += " "
End If
r += Mid(str, i, 1)
End If
Next
End If
Return r
End Function
I think it meets your criteria.
Hope that helps.
Unless using those VB6 methods is a requirement, here's a one-line solution:
TextBox2.Text = String.Join(" ", TextBox1.Text.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries))
Online test: http://ideone.com/gBbi55
String.Split() splits a string on a specific character or substring (in this case a space) and creates an array of the string parts in-between. I.e: "Hello There" -> {"Hello", "There"}
StringSplitOptions.RemoveEmptyEntries removes any empty strings from the resulting split array. Double spaces will create empty strings when split, thus you'll get rid of them using this option.
String.Join() will create a string from an array and separate each array entry with the specified string (in this case a single space).
There is a very simple answer to this question, there is a string method that allows you to remove those "White Spaces" within a string.
Dim text_with_white_spaces as string = "Hey There!"
Dim text_without_white_spaces as string = text_with_white_spaces.Replace(" ", "")
'text_without_white_spaces should be equal to "HeyThere!"
Hope it helped!

Remove Character from First Array and Last Array String

Dim arr() As String
Dim a As Integer
Dim temp As String
Dim temp2 As String
a = 0
Open App.Path & "\EndOfB.txt" For Input As #1
Do While Not EOF(1)
Line Input #1, temp
temp2 = temp2 & "," & temp
a = a + 1
arr = Split(temp2, ",")
Loop
Close #1
Guys how can i remove the character (") in the first and last array? because if i write in a textfile, the first and last string had this character ("). This is the sample output".
"08:01:04
08:16:06
10:52:06
11:52:21"
Thanks in advance Guys. :)
Change your loop to
Do While Not EOF(1)
Line Input #1, temp
temp2 = temp2 & "," & temp
a = a + 1
arr = Split(temp2, ",")
' Strip first character from first array element
arr(LBound(arr)) = Right$(arr(LBound(arr)), Len(arr(LBound(arr)) - 1))
' Strip last character from last array element
arr(UBound(arr)) = Left$(arr(UBound(arr)), Len(arr(UBound(arr)) - 1))
Loop
I had the same problem, I was able to just google it which is what you should do before asking but since I understand and had this problem myself for a little while I will give you a easy example of what do do.
Text1.Text = Mid(Text1.Text, 2)
Text1.Text = Left$(Text1.Text, Len(Text1.Text) - 1)
I Hope this works for you, just replace text1.text with the name of the string you want to edit.

VBA function to convert name format

I want to take a name in First Last format and change it to Last, First. I know I could to this with a formula but I want to be complicated.
Please let me know if you see any red flags in my code, or suggestions for improvements.
Function LastFirst(Name_FL As String)
'This only works if there is a single space in the cell - Will Error If Spaces <> 1
Length = Len(Name_FL) 'Establishes Length of String
Spaces = Length - Len(Application.WorksheetFunction.Substitute(Name_FL, " ", "")) 'Number of spaces
If Spaces <> 1 Then
LastFirst = "#SPACES!#" 'Error Message
Else
SpaceLocation = Application.WorksheetFunction.Find(" ", Name_FL, 1) 'Location of space
Last = Right(Name_FL, Length - SpaceLocation) 'Establishes Last Name String
First = Left(Name_FL, SpaceLocation) 'Establishes First Name String
LastFirst = Application.WorksheetFunction.Proper(Last & ", " & First) 'Puts it together
End If
End Function 'Ta-da
You could simplify it to:
Function LastFirst(Name_FL As String) As String
If (Len(Name_FL) - Len(Replace(Name_FL, " ", ""))) > 1 Then
LastFirst = "#SPACES#"
Else
LastFirst = StrConv(Split(Name_FL, " ")(1) & ", " & Split(Name_FL, " ")(0), vbProperCase)
End If
End Function
The logic here is:
If there is more than 1 space, return the error string #SPACES#
If there is 1 space, the split the string using " " as a delimiter.
Use the second index of the Split array, add ", " and use the first index of the split array.
Use StrConv() to convert it all to proper case.
You might also want to add another check for no spaces:
If InStr(Name_FL, " ") > 0 Then
'// There is a space in the string
Else
'// There is no space in the string
End If
Which can also be tested for by slightly changing the logic of the above example:
Function LastFirst(Name_FL As String) As String
If (Len(Name_FL) - Len(Replace(Name_FL, " ", ""))) = 1 Then
LastFirst = StrConv(Split(Name_FL, " ")(1) & ", " & Split(Name_FL, " ")(0), vbProperCase)
Else
LastFirst = "#SPACES#"
End If
End Function
Further elaboration on functions:
You can see I've used some VBA functions here in place of your WorksheetFunction methods.
Len() returns the Length of a string.
Replace() does what it says on the tin - replaces a given string with another.
StrConv() Converts a String to a respective case (e.g. vbProperCase).
Split() Creates a zero-based single dimension array from a string, by Splitting it on a given delimiter.
Finally - Don't forget to specify a return value in your function header:
Function LastFirst(Name_FL As String)As String<~~ return type